forked from architsingla13/InterviewBit-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBSTIterator.java
More file actions
44 lines (34 loc) · 765 Bytes
/
BSTIterator.java
File metadata and controls
44 lines (34 loc) · 765 Bytes
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
package Trees;
import java.util.Stack;
/**
* Author - archit.s
* Date - 07/11/18
* Time - 1:41 PM
*/
public class BSTIterator {
Stack<TreeNode> s;
TreeNode curr;
public BSTIterator(TreeNode root) {
s = new Stack<>();
curr = root;
while(curr!=null){
s.push(curr);
curr = curr.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !s.empty();
}
/** @return the next smallest number */
public int next() {
curr = s.pop();
int value = curr.val;
curr = curr.right;
while(curr!=null){
s.push(curr);
curr = curr.left;
}
return value;
}
}