就是搜索二叉樹,樹的左兒子比她小,右兒子比她大,本來用遞歸插入,不知道爲什麼輸不出。。。。。。
#include <iostream>
#include <string>
#include <stack>
using namespace std;
struct BinNode
{
char letter;
BinNode *left,*right;
BinNode(char val='*'):letter(val),left(NULL),right(NULL){}
};
class BinTree
{
public:
BinTree():root(NULL){}
void buildtree()
{
string str;
stack<string>s;
while(cin>>str)
{
if(str[0]=='*'||str[0]=='$')
{
while(!s.empty())
{
string x=s.top();
//cout<<x<<endl;
s.pop();
int len=x.size();
for(int i=0;i<len;i++)
{
//cout<<x[i]<<endl;
insert(x[i]);
}
}
if(root==NULL)cout<<"YES\n";
preorder(root);
cout<<endl;
root=NULL;
if(str[0]=='$')return;
}
else s.push(str);
}
}
private:
BinNode *root;
void insert(const char c) {
if (root==NULL)
root=new BinNode(c);
else {
BinNode *ptr=root;
BinNode *pre=NULL;
while (ptr) {
if (ptr->letter==c)
return;
else if(ptr->letter>c) {
pre=ptr;
ptr=ptr->left;
} else {
pre=ptr;
ptr=ptr->right;
}
}
if (pre->letter>c)
pre->left=new BinNode(c);
else
pre->right=new BinNode(c);
}
}
void preorder(BinNode *r)
{
if(r==NULL)return;
cout<<r->letter;
preorder(r->left);
preorder(r->right);
delete r;
}
};
int main()
{
BinTree BT;
BT.buildtree();
return 0;
}