173.Binary Search Tree Iterator
Note: next()
and hasNext()
should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
1-Stack
https://leetcode.com/problems/binary-search-tree-iterator/discuss/52525/
When next() be called, I just pop one element and process its right child as new root.
The code is pretty straightforward.So this can satisfy O(h) memory, hasNext() in O(1) time,
But next() is O(h) time.I can’t find a solution that can satisfy both next() in O(1) time, space in O(h).
The average time complexity of next() function is O(1) indeed in your case. As the next function can be called n times at most, and the number of right nodes in self.pushAll(tmpNode.right) function is maximal n in a tree which has n nodes, so the amortized time complexity is O(1).
Your solution is indeed average O(1) time and O(h) space.
Each node will be visited at most twice-> average O(1) run time.
The stack will store at most h nodes -> O(h) space.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BSTIterator {
private Deque<TreeNode> stack = new ArrayDeque<>();
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){
while(node != null){
stack.push(node);
node = node.left;
}
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/