forked from wey068/Facebook-Interview-Coding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path173. Binary Search Tree Iterator.java
More file actions
104 lines (99 loc) · 2.75 KB
/
Copy path173. Binary Search Tree Iterator.java
File metadata and controls
104 lines (99 loc) · 2.75 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
100
101
102
103
104
173. Binary Search Tree Iterator
public class BSTIterator {
private Stack<TreeNode> stack;
public BSTIterator(TreeNode root) {
stack = new Stack<>();
pushAll(root);
}
public boolean hasNext() {
return !stack.isEmpty();
}
public int next() {
TreeNode node = stack.pop();
pushAll(node.right);
return node.val;
}
private void pushAll(TreeNode node) {
while (node != null) {
stack.push(node);
node = node.left;
}
}
}
******变种******
写个BST的in-order iterator,要写的function有 next() 和 all(), all() return所有剩下的。
public class BSTIterator {
private Stack<TreeNode> stack;
public BSTIterator(TreeNode root) {
stack = new Stack<>();
pushAll(root);
}
private void pushAll(TreeNode node) {
while (node != null) {
stack.push(node);
node = node.left;
}
}
public boolean hasNext() {
return !stack.isEmpty();
}
public TreeNode next() {
TreeNode node = stack.pop();
pushAll(node.right);
return node;
}
public List<TreeNode> all() {
List<TreeNode> res = new ArrayList<>();
while (hasNext())
res.add(next());
return res;
}
}
************Follow up******
改成 preorder 和 postorder。 我全用的stack
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) return res; // corner check
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.empty()) {
res.add(stack.pop().val);
if (root.right != null) stack.push(root.right);
if (root.left != null) stack.push(root.left);
}
return res;
}
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.empty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
res.add(stack.pop().val);
root = root.right;
}
return res;
}
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode prev = null;
while (root != null || !stack.empty()) {
if (root != null) {
stack.push(root);
root = root.left;
} else {
TreeNode tmp = stack.peek();
if (tmp.right != null && tmp.right != prev)
root = tmp.right;
else {
stack.pop();
res.add(tmp.val);
prev = tmp;
}
}
}
return res;
}