-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path145. Binary tree postorder traversal
100 lines (76 loc) · 2.17 KB
/
145. Binary tree postorder traversal
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
88
89
90
91
92
93
94
95
96
97
98
99
100
//145. Binary tree postorder traversal
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
//Solution 1
if(root == null) {
return new ArrayList<>();
}
List<Integer> result = new ArrayList<>();
result.addAll(postorderTraversal(root.left));
result.addAll(postorderTraversal(root.right));
result.add(root.val);
return result;
//Solution 2
List<Integer> post = new ArrayList<>();
if(root == null) {
return post;
}
Stack<TreeNode> st1 = new Stack<>();
Stack<TreeNode> st2 = new Stack<>();
st1.push(root);
while(!st1.isEmpty()) {
root = st1.pop();
st2.push(root);
if(root.left != null) {
st1.push(root.left);
}
if(root.right != null) {
st1.push(root.right);
}
}
while(!st2.isEmpty()) {
post.add(st2.pop().val);
}
return post;
//Solution 3
List<Integer> post = new ArrayList<>();
if(root == null) {
return post;
}
Stack<TreeNode> st = new Stack<>();
TreeNode cur = root;
while(cur != null || !st.isEmpty()) {
if(cur != null) {
st.push(cur);
cur = cur.left;
}
else {
TreeNode temp = st.peek().right;
if(temp == null) {
temp = st.pop();
post.add(temp.val);
while(!st.isEmpty() && temp == st.peek().right) {
temp = st.pop();
post.add(temp.val);
}
}
else {
cur = temp;
}
}
}
return post;
}
}