-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBSTIterator.java
More file actions
53 lines (45 loc) · 1.11 KB
/
BSTIterator.java
File metadata and controls
53 lines (45 loc) · 1.11 KB
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
/**
*
*/
package cc.dectinc.leetcode;
import cc.dectinc.api.structs.TreeNode;
import java.util.Stack;
/**
* @author Dectinc
* @version Apr 20, 2015 9:12:30 PM
*/
public class BSTIterator {
Stack<TreeNode> stack;
public BSTIterator(TreeNode root) {
stack = new Stack<TreeNode>();
allLeftIntoStack(root);
}
/**
* @return whether we have a next smallest number
*/
public boolean hasNext() {
return stack.size() > 0;
}
/**
* @return the next smallest number
*/
public int next() {
TreeNode node = stack.pop();
allLeftIntoStack(node.right);
return node.val;
}
private void allLeftIntoStack(TreeNode node) {
while (node != null) {
stack.add(node);
node = node.left;
}
}
public static void main(String[] args) {
TreeNode root = TreeNode.constructTreeWithLevelTraversal(new Integer[]{
2, 1});
BSTIterator iter = new BSTIterator(root);
while (iter.hasNext()) {
System.out.print("" + iter.next() + "\t");
}
}
}