forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution9.java
65 lines (55 loc) · 1.63 KB
/
Solution9.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/// Source : https://leetcode.com/problems/binary-tree-postorder-traversal/description/
/// Author : liuyubobobo
/// Time : 2018-05-31
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;
// Morris PostOrder Traversal
//
// Time Complexity: O(n)
// Space Complexity: O(1)
public class Solution9 {
public List<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<Integer>();
if(root == null)
return res;
TreeNode dummyRoot = new TreeNode(-1);
dummyRoot.left = root;
TreeNode cur = dummyRoot;
while(cur != null){
if(cur.left == null)
cur = cur.right;
else{
TreeNode pre = cur.left;
while(pre.right != null && pre.right != cur)
pre = pre.right;
if(pre.right == null){
pre.right = cur;
cur = cur.left;
}
else{
pre.right = null;
reverseTraversal(cur.left, res);
cur = cur.right;
}
}
}
return res;
}
private void reverseTraversal(TreeNode node, ArrayList<Integer> res){
int start = res.size();
while(node != null){
res.add(node.val);
node = node.right;
}
int i = start, j = res.size() - 1;
while(i < j){
Integer t = res.get(i);
res.set(i, res.get(j));
res.set(j, t);
i ++;
j --;
}
}
}