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;
};