-
Notifications
You must be signed in to change notification settings - Fork 13
/
Problem_3_Binary_Search_Tree_Iterator.java
47 lines (37 loc) · 1.1 KB
/
Problem_3_Binary_Search_Tree_Iterator.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
package Concurrency;
// Problem Statement: Binary Search Tree Iterator (medium)
// LeetCode Question: 173. Binary Search Tree Iterator
import java.util.Stack;
public class Problem_3_Binary_Search_Tree_Iterator {
class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
this.left = null;
this.right = null;
}
}
private Stack<TreeNode> stack = new Stack<TreeNode>();
public Problem_3_Binary_Search_Tree_Iterator(TreeNode root) {
traverseLeft(root);
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode tmpNode = stack.pop();
traverseLeft(tmpNode.right);
return tmpNode.val;
}
/** traverse the left sub-tree to push all nodes on the stack */
private void traverseLeft(TreeNode node) {
while(node != null){
stack.push(node);
node = node.left;
}
}
}