-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBSTIterator
56 lines (50 loc) · 1.2 KB
/
BSTIterator
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
/*
Definition of Node class for reference
class TreeNode<T>
{
public T data;
public TreeNode<T> left;
public TreeNode<T> right;
TreeNode(T data)
{
this.data = data;
left = null;
right = null;
}
}
*/
import java.util.*;
public class Solution {
static class BSTIterator{
Stack<TreeNode<Integer>> stack;
BSTIterator(TreeNode<Integer> root){
stack = new Stack<>();
pushAll(root);
}
public void pushAll(TreeNode<Integer> node){
while(node!=null){
stack.push(node);
node = node.left;
}
}
int next(){
TreeNode<Integer> node = stack.pop();
if(node.right!=null){
pushAll(node.right);
}
return node.data;
}
boolean hasNext(){
// Write your code here
return !stack.isEmpty();
}
}
}
/*
Your BSTIterator object will be instantiated and called as such:
BSTIterator iterator = new BSTIterator(root);
while(iterator.hasNext())
{
print(iterator.next()+" ");
}
*/