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.
class BSTIterator {
public:
BSTIterator(TreeNode *root){
while(root)
{
inorder.push(root);
root = root->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
return inorder.empty() ? false : true;
}
/** @return the next smallest number */
int next() {
TreeNode *cur = inorder.top();
inorder.pop();
if(cur->right)
{
TreeNode *temp = cur->right;
while(temp)
{
inorder.push(temp);
temp = temp->left;
}
}
return cur->val;
}
private:
stack<TreeNode *> inorder;
};