next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
You may assume that next() call will always be valid, that is, there will be at least a next smallest number in the BST when next() is called.
Solution
C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class BSTIterator {
stack<TreeNode*> nodes;
TreeNode* current;
public:
BSTIterator(TreeNode* root) : current(nullptr) {
while (root != nullptr) {
nodes.push(root);
root = root->left;
}
}
/** @return the next smallest number */
int next() {
while (current != nullptr) {
nodes.push(current);
current = current->left;
}
TreeNode* next = nodes.top();
nodes.pop();
current = next->right;
return next->val;
}
/** @return whether we have a next smallest number */
bool hasNext() {
return (current != nullptr || !nodes.empty());
}
};
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator* obj = new BSTIterator(root);
* int param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/
Python3
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class BSTIterator:
def __init__(self, root: TreeNode):
self.current = None
self.nodes = list()
while root:
self.nodes.append(root)
root = root.left
def next(self) -> int:
"""
@return the next smallest number
"""
while self.current:
self.nodes.append(self.current)
self.current = self.current.left
next_el = self.nodes.pop()
self.current = next_el.right
return next_el.val
def hasNext(self) -> bool:
"""
@return whether we have a next smallest number
"""
return self.current or self.nodes
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()