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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
思路:已知是二叉搜索树,它是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它
的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。
因此可以中序遍历,将结点放在向量中,再从头到尾输出一边即可。
class BSTIterator {
public:
BSTIterator(TreeNode *root) {
pos = 0;
path(root);
}
void path(TreeNode* root)
{
if(root)
{
if(root->left)
path(root->left);
v.push_back(root->val);
if(root->right)
path(root->right);
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
return pos<v.size();
}
/** @return the next smallest number */
int next() {
return v[pos++];
}
private:
vector<int> v;
int pos;
};
本文介绍了一种针对二叉搜索树(BST)的迭代器实现方法,该迭代器能够以平均O(1)的时间复杂度返回BST中的下一个最小值,并使用O(h)的空间复杂度,其中h为树的高度。通过中序遍历的方式,将节点值存储在向量中,确保每次调用都能高效获取下一个元素。
595

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



