1.使用栈
代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
//二叉搜索树的中序是升序
stack<int> s;
public:
void inOreder(TreeNode *root)
{
if(root==NULL)
return ;
inOreder(root->right);
s.push(root->val);
inOreder(root->left);
}
BSTIterator(TreeNode* root) {
inOreder(root);
}
/** @return the next smallest number */
int next() {
int res=0;
if(!s.empty())
{
res=s.top();
s.pop();
}
return res;
}
/** @return whether we have a next smallest number */
bool hasNext() {//判断是否还有下一个最小数
if(!s.empty())
return true;
return false;
}
};
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator* obj = new BSTIterator(root);
* int param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/
新增了一个函数
2.使用栈,不增加函数
首先将节点的左子树入栈,直到左子树为空,此时,栈顶元素为最小值
出栈时,当前节点首先出栈,然后判断当前节点是否有右子树,其右子树的值都大于当前节点的值但小于当前节点的父节点的值,故当前节点出现后,需要将当前节点的右子树入栈
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
//二叉搜索树的中序是升序
stack<TreeNode*> s;
public:
BSTIterator(TreeNode* root) {
while(root)
{
s.push(root);
root=root->left;
}
}
/** @return the next smallest number */
int next() {//栈顶元素为当前最小元素
TreeNode *t=s.top();
s.pop();
int val=t->val;
t=t->right;
while(t)//检查当前节点是否有左子树,左子树的节点都比它大,但比它的父亲小,故当前节点出栈后,需要将其右边的所有节点入栈
{
s.push(t);
t=t->left;
}
return val;
}
/** @return whethe we have a next smallest number */
bool hasNext() {//判断是否还有下一个最小数
if(!s.empty())
return true;
return false;
}
};
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator* obj = new BSTIterator(root);
* int param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/