-
Notifications
You must be signed in to change notification settings - Fork 13
/
PreorderTraversal144.java
102 lines (96 loc) · 2.43 KB
/
PreorderTraversal144.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
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
101
102
package Leetcode;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
public class PreorderTraversal144 {
/**Method 1: Iteration; Time:O(N); Space:O(N) **/
public List<Integer> preorderTraversal1(TreeNode root) {
List<Integer> res = new ArrayList<>();
preorder(root, res);
return res;
}
private void preorder(TreeNode node, List<Integer> list) {
if(node == null) {
return;
}
list.add(node.val);
preorder(node.left, list);
preorder(node.right, list);
}
/**Method 2: Not Iteration - Queue; Time:O(N); Space:O(N) **/
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root == null) {
return res;
}
Deque<TreeNode> q = new LinkedList<>();
while(!q.isEmpty() || root!=null) {
while(root!=null) {
q.push(root);
res.add(root.val);
root = root.left;
}
root = q.pop();
root = root.right;
}
return res;
}
/**Method 3: Morris; Time:O(N); Space:O(1) **/
public List<Integer> preorderTraversal3(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root == null) {
return res;
}
TreeNode cur = root, mostRight = null;
while(cur != null) {
mostRight = cur.left;
if(mostRight != null) {
while(mostRight.right != null && mostRight.right != cur) {
mostRight = mostRight.right;
}
if(mostRight.right == null) {
res.add(cur.val);
mostRight.right = cur;
cur = cur.left;
continue;
} else {
mostRight = null;
}
} else {
res.add(cur.val);
}
cur = cur.right;
}
return res;
}
public void addPath(List<Integer> res, TreeNode node) {
int count = 0;
while (node != null) {
++count;
res.add(node.val);
node = node.right;
}
int left = res.size() - count, right = res.size() - 1;
while (left < right) {
int temp = res.get(left);
res.set(left, res.get(right));
res.set(right, temp);
left++;
right--;
}
}
//Definition for a binary tree node.
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;
}
}
}