173. 二叉搜索树迭代器
实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。
调用 next() 将返回二叉搜索树中的下一个最小的数。
示例:
BSTIterator iterator = new BSTIterator(root);
iterator.next(); // 返回 3
iterator.next(); // 返回 7
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 9
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 15
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 20
iterator.hasNext(); // 返回 false
class BSTIterator {
private:
vector<TreeNode*> S;
public:
BSTIterator(TreeNode* root){
while(root){
S.push_back(root);
root = root->left;
}
}
int next() {
TreeNode* t = S.back();
S.pop_back();
int val = t->val;
t = t->right;
while(t){
S.push_back(t);
t = t->left;
}
return val;
}
bool hasNext() {
return !S.empty();
}
};
测试代码:
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
struct TreeNode {
char data;
TreeNode *left;
TreeNode *right;
};
typedef TreeNode* BTree;
class BSTIterator {
private:
vector<TreeNode*> S;
TreeNode* root;
public:
void init(){
root=CreateBTree();
TreeNode* troot=root;
while(troot){
S.push_back(troot);
troot = troot->left;
}
}
char next() {
TreeNode* t = S.back();
S.pop_back();
char val = t->data;
t = t->right;
while(t){
S.push_back(t);
t = t->left;
}
return val;
}
bool hasNext() {
return !S.empty();
}
BTree CreateBTree()
{
BTree bt = NULL;
char ch;
cin>>ch;
if (ch != '#')
{
bt = new TreeNode;
bt->data = ch;
bt->left = CreateBTree();
bt->right = CreateBTree();
}
return bt;
}
//层序遍历
void LevelOrder(){
queue<TreeNode*>q;
TreeNode *front;
if(root==NULL)return;
q.push(root);
while (!q.empty())
{
front = q.front();
q.pop();
if (front->left)
{
q.push(front->left);
}
if (front->right)
{
q.push(front->right);
}
cout<<front->data;
}
}
};
int main(){
BSTIterator iterator;
iterator.init();
iterator.LevelOrder();
cout<<endl;
cout<<iterator.next()<<endl;
cout<<iterator.hasNext()<<endl;
cout<<iterator.next()<<endl;
cout<<iterator.hasNext()<<endl;
cout<<iterator.next()<<endl;
cout<<iterator.hasNext()<<endl;
}
12##3##
因上求缘,果上努力~~~~ 作者:图神经网络,转载请注明原文链接:https://www.cnblogs.com/BlairGrowing/p/13524045.html