forked from soulmachine/algorithm-essentials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-tree-postorder-traversal-2.java
More file actions
64 lines (58 loc) · 1.92 KB
/
Copy pathbinary-tree-postorder-traversal-2.java
File metadata and controls
64 lines (58 loc) · 1.92 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
// Binary Tree Postorder Traversal
// Morris后序遍历,时间复杂度O(n),空间复杂度O(1)
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<>();
TreeNode dummy = new TreeNode(-1);
dummy.left = root;
TreeNode cur = dummy;
TreeNode prev = null;
while (cur != null) {
if (cur.left == null) {
prev = cur; /* 必须要有 */
cur = cur.right;
} else {
TreeNode node = cur.left;
while (node.right != null && node.right != cur)
node = node.right;
if (node.right == null) { /* 还没线索化,则建立线索 */
node.right = cur;
prev = cur; /* 必须要有 */
cur = cur.left;
} else { /* 已经线索化,则访问节点,并删除线索 */
visit_reverse(cur.left, prev, result);
prev.right = null;
prev = cur; /* 必须要有 */
cur = cur.right;
}
}
}
return result;
}
// 逆转路径
private static void reverse(TreeNode from, TreeNode to) {
TreeNode x = from;
TreeNode y = from.right;
TreeNode z = null;
if (from == to) return;
while (x != to) {
z = y.right;
y.right = x;
x = y;
y = z;
}
}
// 访问逆转后的路径上的所有结点
private static void visit_reverse(TreeNode from, TreeNode to,
List<Integer> result) {
TreeNode p = to;
reverse(from, to);
while (true) {
result.add(p.val);
if (p == from)
break;
p = p.right;
}
reverse(to, from);
}
}