forked from walnutown/CodingInTheDeep
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreePostorderTraversal.java
More file actions
100 lines (94 loc) · 2.95 KB
/
Copy pathBinaryTreePostorderTraversal.java
File metadata and controls
100 lines (94 loc) · 2.95 KB
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
/*
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// Stack Iterative traversal.
// time: O(n); space: O(h), h is the maximum height of the tree
public class Solution {
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<Integer>();
if (root == null) return res;
Stack<TreeNode> st = new Stack<TreeNode>();
Stack<Integer> reverse = new Stack<Integer>();
while (root != null || !st.isEmpty()){
if (root == null) root = st.pop();
reverse.push(root.val);
if (root.left != null) st.push(root.left);
root = root.right;
}
while (!reverse.isEmpty()) res.add(reverse.pop());
return res;
}
}
// Stack Iterative traversal, from Sophie. 2 while loops, logic is easier to understand.
// post-order: left -> right -> curr
// pre-order: curr -> left -> right
// mirror of pre-order: curr -> right -> left. Reverse to get the post-order
// And in this solution, we use Collections.reverse() instead of Stack to get the reversed result
public class Solution{
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<Integer>();
if (root == null) return res;
Stack<TreeNode> st = new Stack<TreeNode>();
while (root != null){
st.push(root);
res.add(root.val);
root = root.right;
}
while (!st.isEmpty()){
TreeNode curr = st.pop();
curr = curr.left;
while (curr != null){
st.push(curr);
res.add(curr.val);
curr = curr.right;
}
}
Collections.reverse(res);
return res;
}
}
// Morris traversal
// mirror preorder morris traversal and finally reverse the result
public class Solution{
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<Integer>();
TreeNode curr = root;
while (curr!=null){
if (curr.right==null){
res.add(curr.val);
curr = curr.left;
}else{
TreeNode prev = curr.right;
while (prev.left!=null && prev.left!=curr)
prev = prev.left;
if (prev.left==null){
prev.left = curr;
res.add(curr.val);
curr = curr.right;
}else{
prev.left = null;
curr = curr.left;
}
}
}
Collections.reverse(res);
return res;
}
}