题解:首先将所有字母存入一个字符数组中,然后从后往前开始建树,使用的是指针。
附上代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=1005;
char s[maxn];
struct node{
char val;
node *lch,*rch;
};
node* insert(node *p,char val)
{
if(p==NULL){
node *q=new node;
q->val=val;
q->lch=q->rch=NULL;
return q;
}else{
if(val<p->val){
p->lch=insert(p->lch,val);
}else{
p->rch=insert(p->rch,val);
}
return p;
}
}
void show(node *p)
{
if(p==NULL){
return ;
}else{
cout<<p->val;
show(p->lch);
show(p->rch);
}
}
int main()
{
while(cin>>s){
int len=strlen(s);
char str;
while(1){
cin>>str;
if(str=='*'||str=='$'){
break;
}
s[len++]=str;
}
node *p=NULL;
while(len-->0){
p=insert(p,s[len]);
}
show(p);
cout<<endl;
}
return 0;
}