题目描述:
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) {
p=root;
}
/** @return whether we have a next smallest number */
bool hasNext() {
if(s.size()>0||p!=NULL) return true;
else return false;
}
/** @return the next smallest number */
int next() {
while(p!=NULL)
{
s.push(p);
p=p->left;
}
int result=0;
if(s.size()>0)
{
p=s.top();
result=p->val;
s.pop();
p=p->right;
}
return result;
}
private:
TreeNode* p;
stack<TreeNode*> s;
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/
本文介绍了一种在二叉搜索树(BST)上进行中序遍历的迭代器实现方法。该迭代器初始化时接收BST的根节点,并提供next()和hasNext()方法,分别用于返回下一个最小值和判断是否还有更多元素。实现平均O(1)时间复杂度和O(h)空间复杂度,其中h为树的高度。
1247

被折叠的 条评论
为什么被折叠?



