173. Binary Search Tree Iterator
173. Binary Search Tree Iterator
Implement the BSTIterator
class that represents an iterator over the in-order traversal of a binary search tree (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.
Example 1:
Input
["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]
Output
[null, 3, 7, true, 9, true, 15, true, 20, false]
Explanation
BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);
bSTIterator.next(); // return 3
bSTIterator.next(); // return 7
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 9
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 15
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 20
bSTIterator.hasNext(); // return False
My Solutions:
把节点和节点的左节点全部塞进stack里,这样保证next()时从stack里pop()出来的是最小节点。之后把pop出来的节点的右节点再加入stack。
比如例子里的树
一开始stack里只有【7,3】
next()的时候pop出3
再次next()的时候pop出7,这时候把15,9加入stack
下一次next()的时候pop出9 。。。。。。
public class BSTIterator {
private Stack<TreeNode> stack = new Stack<>();
public void addNode(TreeNode root) {
while (root != null) {
stack.push(root);
root = root.left;
}
}
public BSTIterator(TreeNode root) {
addNode(root);
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode next = stack.pop();
addNode(next.right);
return next.val;
}
}
Last updated