173. Binary Search Tree Iterator

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
class BSTIterator {

private final Stack<TreeNode> stack;

public BSTIterator(TreeNode root) {
this.stack = new Stack<>();
pushTreeToStack(root);
}

private void pushTreeToStack(TreeNode root) {
while (root != null) {
stack.push(root);
root = root.left;
}
}

public int next() {
TreeNode root = stack.pop();
pushTreeToStack(root.right);
return root.val;
}

public boolean hasNext() {
return !stack.isEmpty();
}

}

References

173. Binary Search Tree Iterator
剑指 Offer II 055. 二叉搜索树迭代器