173. Binary Search Tree Iterator
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.
这里的要求是每次调用next(),只用O(1)的时间,存储空间只能是O(h)。BST的特点,左根树都比根节点小,右子树都比根节点大。
思路:用一个栈存储当前节点开始的所有左侧节点,如果要输出next(),栈弹出当前节点后,再对该节点的右节点进行操作,即把这个右节点的所有左侧节点存入栈中,保证下次弹出的是比当前大而比其他都小的节点值。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
stack<TreeNode*> stk;
public:
BSTIterator(TreeNode *root) {
pushall(root);
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !stk.empty();
}
/** @return the next smallest number */
int next() {
TreeNode* tmp=stk.top();
stk.pop();
pushall(tmp->right);
return tmp->val;
}
/
void pushall(TreeNode* root)
{
while(root)
{
stk.push(root);
root=root->left;
}
}
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/