-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructy-119-postOrder.js
87 lines (68 loc) · 1.6 KB
/
structy-119-postOrder.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// https://structy.net/problems/premium/post-order
class Node {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
// p: root of bi tree
// r: arr
// in-order
const postOrder = (root) => {
if (!root) return [];
const left = postOrder(root.left);
const right = postOrder(root.right);
// const arr = left.concat(right);
// arr.push(root.val);
const arr = [...left, root.val, ...right];
return arr;
};
// // pre-order
// const postOrder = (root) => {
// if (!root) return [];
// const left = postOrder(root.left);
// const right = postOrder(root.right);
// const arr = left.concat(right);
// arr.unshift(root.val);
// return arr;
// };
// // post-order
// const postOrder = (root) => {
// if (!root) return [];
// const left = postOrder(root.left);
// const right = postOrder(root.right);
// const arr = left.concat(right);
// arr.push(root.val);
// return arr;
// };
// const x = new Node("x");
// const y = new Node("y");
// const z = new Node("z");
// x.left = y;
// x.right = z;
// // x
// // / \
// // y z
// postOrder(x);
// // ['y', 'z', 'x']
const a = new Node("a");
const b = new Node("b");
const c = new Node("c");
const d = new Node("d");
const e = new Node("e");
const f = new Node("f");
const g = new Node("g");
a.left = b;
a.right = c;
b.left = d;
b.right = e;
c.left = f;
c.right = g;
// a
// / \
// b c
// / \ / \
// d e f g
console.log(postOrder(a));
// [ 'd', 'e', 'b', 'f', 'g', 'c', 'a' ]