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()返回二叉搜索树中下一个最小树。有一个注意点:next()和hasNext()应该满足O(1)的时间复杂度和O(h)的空间复杂度,其中h是二叉搜索树的高度。
- 其实很容易发现这道题考查的是非递归方式的中序遍历。内置一个栈,初始化时,从根节点出发,所遇结点的左孩子入栈。
- next()直接取栈顶元素,同时将该栈顶元素弹出。另外,若该栈顶结点存在右孩子,则从右孩子出发,所遇结点的左孩子入栈。
- hasNext()直接对栈判空即可。
下面贴上代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
public:
stack<TreeNode*> s;
BSTIterator(TreeNode *root) {
while(root){
s.push(root);
root=root->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !s.empty();
}
/** @return the next smallest number */
int next() {
TreeNode* tn=s.top();
s.pop();
int ans=tn->val;
if(tn->right){
tn=tn->right;
while(tn){
s.push(tn);
tn=tn->left;
}
}
return ans;
}
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/