Binary Search Tree Iterator

时间:2020-11-30 05:19:34

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.

采用中序遍历将节点压入栈中,由于要求存储空间为O(h),因此不能在一开始将所有节点全部压入,只是压入最左边一列。当取出一个节点时,压入其右子节点的所有左节点。

 /**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
private:
stack <TreeNode*> stk;
int minres;
public:
BSTIterator(TreeNode *root) {
while(root)
{
stk.push(root);
root=root->left;
}
} /** @return whether we have a next smallest number */
bool hasNext() {
if(stk.empty())
return false;
TreeNode* top;
top=stk.top();
minres=top->val;
stk.pop();
TreeNode* cur=top->right;
if(cur)
{
stk.push(cur);
cur=cur->left;
while(cur)
{
stk.push(cur);
cur=cur->left;
}
}
return true;
} /** @return the next smallest number */
int next() {
return minres;
}
}; /**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/