Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
Solution:Stack
思路: 索性都放在stack较好实现,instead of 留出一个current
hasNext() Time Complexity: O(1)
next() Time Complexity: worst O(h) if nearly balanced; amortized(average): O(1)
Space Complexity: O(N)
Solution Code:
public class BSTIterator {
private Deque<TreeNode> stack = new ArrayDeque<TreeNode>();
public BSTIterator(TreeNode root) {
pushAll(root);
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode tmpNode = stack.pop();
pushAll(tmpNode.right);
return tmpNode.val;
}
private void pushAll(TreeNode node) {
for (; node != null; stack.push(node), node = node.left);
}
}