-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathMorrisTraversal.java
74 lines (63 loc) · 1.84 KB
/
MorrisTraversal.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
66
67
68
69
70
71
72
73
74
// Asked in Josh Technologies Group
import java.util.*;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
this.left = null;
this.right = null;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class MorrisTraversal {
static List<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<>();
TreeNode curr = root;
while (curr != null) {
// Left subtree empty
if (curr.left == null) {
result.add(curr.val);
curr = curr.right;
}
// Left subtree exists
else {
// Find curr's predecessor(go 1 left and right until null)
TreeNode prev = curr.left;
while (prev.right != null && prev.right != curr) {
prev = prev.right;
}
// Make thread and move curr
if (prev.right == null) {
prev.right = curr;
curr = curr.left;
}
// Break thread
else {
prev.right = null;
result.add(curr.val);
curr = curr.right;
}
}
}
return result;
}
public static void main(String[] args)
{
// 1
// 2 3
// 5 4
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.left.right = new TreeNode(5);
root.right = new TreeNode(3);
root.right.right = new TreeNode(4);
List<Integer> result = inorderTraversal(root);
System.out.println(result);
}
}