-
Notifications
You must be signed in to change notification settings - Fork 34
/
Solution.java
57 lines (53 loc) · 1.37 KB
/
Solution.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
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BSTIterator {
List<TreeNode> list=new ArrayList<TreeNode>();
public BSTIterator(TreeNode root) {
if(root!=null){
list.add(root);
}
while(list.size()>0){
TreeNode node=list.get(list.size()-1);
if(node.left!=null){
list.add(node.left);
node.left=null;
}else{
break;
}
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return list.size()!=0;
}
/** @return the next smallest number */
public int next() {
TreeNode test=list.get(list.size()-1);
list.remove(list.size()-1);
if(test.right!=null){
list.add(test.right);
while(true){
TreeNode node=list.get(list.size()-1);
if(node.left!=null){
list.add(node.left);
node.left=null;
}else {
break;
}
}
}
return test.val;
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/