Binary Tree Postorder Traversal LeetCode solution in JavaScript

1
class Pair {
2
constructor(node, state) {
3
this.node = node;
4
this.state = state;
5
}
6
}
7
var postorderTraversal = function (root) {
8
let ans = [];
9
let st = []; // stack
10
root != null && st.push(new Pair(root, 1));
11

12
while (st.length > 0) {
13
let top = st[st.length - 1];
14

15
if (top.state == 1) {
16
top.state++;
17
if (top.node.left != null) {
18
st.push(new Pair(top.node.left, 1));
19
}
20
} else if (top.state == 2) {
21
top.state++;
22
if (top.node.right != null) {
23
st.push(new Pair(top.node.right, 1));
24
}
25
} else {
26
ans.push(top.node.val);
27
st.pop();
28
}
29
}
30
return ans;
31
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0