题目描述
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.
思想:
中序遍历的拆分。用栈保存路径,但是并非一次性遍历所有的节点,不然存储空间太大。每次只保存左侧节点到最底层节点。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
public:
BSTIterator(TreeNode *root) {
TreeNode *p = root;
while(p)//左节点不断入栈,相当于寻找中序遍历的第一个元素
{
temp.push(p);
p = p->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !temp.empty();
}
/** @return the next smallest number */
int next() {
TreeNode *q = temp.top();
int x = q->val;
temp.pop();
q=q->right;
while(q)//继续把右节点的左侧遍历入栈
{
temp.push(q);
q = q->left;
}
return x;
}
private:
stack<TreeNode *> temp;
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/