-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathBinary Tree Postorder Traversal - Solution I.java
50 lines (50 loc) · 1.43 KB
/
Binary Tree Postorder Traversal - Solution I.java
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
import java.util.ArrayList;
import lintcode.util.TreeNode;
import java.util.Stack;
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: Postorder in ArrayList which contains node values.
*/
public ArrayList<Integer> postorderTraversal(TreeNode root) {
// write your code here
ArrayList<Integer> rst = new ArrayList<Integer>();
if (root == null) {
return rst;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
TreeNode cur = root;
TreeNode prev = null;
while (!stack.isEmpty()) {
cur = stack.peek();
if (prev == null || prev.left == cur || prev.right == cur) {
if (cur.left != null) {
stack.push(cur.left);
} else if (cur.right != null) {
stack.push(cur.right);
}
} else if (cur.left == prev) {
if (cur.right != null) {
stack.push(cur.right);
}
} else {
rst.add(cur.val);
stack.pop();
}
prev = cur;
}
return rst;
}
}