-
Notifications
You must be signed in to change notification settings - Fork 0
/
P148.java
57 lines (47 loc) · 1.1 KB
/
P148.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
48
49
50
51
52
53
54
55
56
57
import java.util.*;
import java.io.*;
/*
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;
}
}
*/
public class P148 {
static class BSTIterator {
Stack<TreeNode<Integer>> stk = new Stack<>();
BSTIterator(TreeNode<Integer> root) {
pushAll(root);
}
int next() {
TreeNode<Integer> top = stk.pop();
pushAll(top.right);
return top.data;
}
boolean hasNext() {
return !stk.isEmpty();
}
void pushAll(TreeNode<Integer> node) {
while (node != null) {
stk.push(node);
node = node.left;
}
}
}
}
/*
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator iterator = new BSTIterator(root);
* while(iterator.hasNext())
* {
* print(iterator.next()+" ");
* }
*/