-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchTreeIterator.java
More file actions
41 lines (34 loc) · 1.08 KB
/
BinarySearchTreeIterator.java
File metadata and controls
41 lines (34 loc) · 1.08 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
public class BinarySearchTreeIterator {
public class BSTIterator {
private Deque<TreeNode> queue;
public BSTIterator(TreeNode root) {
this.queue = new ArrayDeque<TreeNode>();
if(root != null){
this.queue.push(root);
TreeNode left = root.left;
while(left != null){
this.queue.push(left);
left = left.left;
}
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return this.queue.size() > 0;
}
/** @return the next smallest number */
public int next() {
TreeNode node = this.queue.poll();
TreeNode right = node.right;
if(right != null){
this.queue.push(right);
TreeNode left = right.left;
while(left != null){
queue.push(left);
left = left.left;
}
}
return node.val;
}
}
}