Skip to content

Commit 1e717e4

Browse files
committed
Two-Hundred-Sixty Commit: Add Binary Search Tree Iterator problem to Concurrency section
1 parent 1869e07 commit 1e717e4

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package Concurrency;
2+
3+
// Problem Statement: Binary Search Tree Iterator (medium)
4+
// LeetCode Question: 173. Binary Search Tree Iterator
5+
6+
import java.util.Stack;
7+
8+
public class Problem_3_Binary_Search_Tree_Iterator {
9+
10+
class TreeNode {
11+
int val;
12+
TreeNode left;
13+
TreeNode right;
14+
public TreeNode(int val) {
15+
this.val = val;
16+
this.left = null;
17+
this.right = null;
18+
}
19+
}
20+
21+
private Stack<TreeNode> stack = new Stack<TreeNode>();
22+
23+
public Problem_3_Binary_Search_Tree_Iterator(TreeNode root) {
24+
traverseLeft(root);
25+
}
26+
27+
/** @return whether we have a next smallest number */
28+
public boolean hasNext() {
29+
return !stack.isEmpty();
30+
}
31+
32+
/** @return the next smallest number */
33+
public int next() {
34+
TreeNode tmpNode = stack.pop();
35+
traverseLeft(tmpNode.right);
36+
return tmpNode.val;
37+
}
38+
39+
/** traverse the left sub-tree to push all nodes on the stack */
40+
private void traverseLeft(TreeNode node) {
41+
while(node != null){
42+
stack.push(node);
43+
node = node.left;
44+
}
45+
}
46+
47+
}

0 commit comments

Comments
 (0)