forked from chihungyu1116/leetcode-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path145 Binary Tree Post Order Traversal.js
48 lines (42 loc) · 1.17 KB
/
145 Binary Tree Post Order Traversal.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
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var postorderTraversal = function(root) {
var result = [];
var stack = [];
var prev = null;
var curr = null;
if(root === null) {
return result;
}
stack.push(root);
// use prev and curr to figure out the direction of tree traversal
while(stack.length !== 0) {
curr = stack[stack.length - 1];
if(prev === null || prev.left === curr || prev.right === curr) { // traverse down the tree
if(curr.left !== null) {
stack.push(curr.left);
} else if(curr.right !== null) {
stack.push(curr.right);
}
} else if(curr.left === prev) { //traverse up the tree from the left
if(curr.right !== null) {
stack.push(curr.right);
}
} else {
// it means that curr === prev
result.push(curr.val);
stack.pop();
}
prev = curr;
}
return result;
};