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.
首先 in order traversal
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
Stack<TreeNode> parentStack = new Stack<TreeNode>();
ArrayList<Integer> result = new ArrayList<Integer>();
while(root!=null||!parentStack.isEmpty()){
while(root!=null){
parentStack.push(root);
root=root.left;
}
root = parentStack.pop();
result.add(root.val);
root = root.right;
}
return result;
}
}
然后 Binary Search Tree Iterator
public class BSTIterator {
Stack<TreeNode> parentstack = new Stack<>();
TreeNode crt ;
public BSTIterator(TreeNode root) {
crt = root;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return (crt!=null || !parentstack.isEmpty());
}
/** @return the next smallest number */
public int next() {
int result=0;
while(crt!=null){
parentstack.push(crt);
crt=crt.left;
}
crt = parentstack.pop();
result = crt.val;
crt= crt.right;
return result;
}
}