题目链接:https://leetcode.com/problems/binary-search-tree-iterator/?tab=Description
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) {
while(root)
{
stk.push(root);
root=root->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
if(!stk.empty())
{
TreeNode* top=stk.top();
stk.pop();
nextmin=top->val;
TreeNode* cur=top->right;
if(cur)
{
stk.push(cur);
cur=cur->left;
while(cur)
{
stk.push(cur);
cur=cur->left;
}
}
return true;
}
else
return false;
}
/** @return the next smallest number */
int next() {
return nextmin;
}
private:
stack<TreeNode *> stk;
int nextmin;
};
方法二:
class BSTIterator {
public:
BSTIterator(TreeNode *root) {
while(root)
{
stk.push(root);
root=root->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
if(!stk.empty())
{
TreeNode* top=stk.top();
stk.pop();
nextmin=top->val;
TreeNode* cur=top->right;
while(cur)
{
stk.push(cur);
cur=cur->left;
}
return true;
}
else
return false;
}
/** @return the next smallest number */
int next() {
return nextmin;
}
private:
stack<TreeNode *> stk;
int nextmin;
};
方法三:
lass BSTIterator{
public:
BSTIterator(TreeNode *root){
bucket=inordertraverse(root);
}
bool hasNext(){
if(k<bucket.size())
return true;
return false;
}
int next(){
return bucket[k++];
}
private:
vector<int> bucket;
int k=0;
vector<int> inordertraverse(TreeNode *root)
{
vector<int> res;
stack<TreeNode*> sta;
TreeNode *p=root;
while(p!=NULL || !sta.empty())
{
while(p!=NULL)
{
sta.push(p);
p=p->left;
}
if(!sta.empty())
{
TreeNode *tmp=sta.top();
res.push_back(tmp->val);
sta.pop();
p=tmp->right;
}
}
return res;
}
};