题意:
将一棵二叉查找树的所有叶子节点去掉(Falling Leaves)
按照顺序用一个字符串给出
再将剩下的树如上操作,直到根节点被作为字符串给出。
任务是还原这棵树,并先根遍历输出。
一道入门的二叉查找树问题 ,主要就是考查插入操作。
关键还是要注意字符型二维数组的操作。
之前就是因为忘了给内循环计数器归零 调试了好久才解决。
#include<iostream>
using namespace std;
char str[26][26];
struct node{
char data;
node* left;
node* right;
};
node* root=new node;
void Insert(node* p){
node* y = NULL;
node* x = root;
while(x!=NULL){
y=x;
if((p->data)<(x->data)) x=x->left;
else x=x->right;
}
if(y==NULL){
root=p;
}
else if(p->data<y->data){
y->left=p;
}
else{
y->right=p;
}
}
void perorder(node* p){
if(p!=NULL){
cout<<p->data;
perorder(p->left);
perorder(p->right);
}
}
int main(){
while(1){
int i=0;
int j=0;
int k=0;
int count=0;
scanf("%s",&str[i]);
while(str[i][0]!='*'&&str[i][0]!='$'){
i++;
scanf("%s",&str[i]);
}
k=i-1;
root->data=str[k][0];
root->left=NULL;
root->right=NULL;
k--;
while(k>=0){
j=0;
while(str[k][j]!='\0'){
node* s=new node;
s->left=NULL;
s->right=NULL;
s->data=str[k][j];
Insert(s);
j++;
}
k--;
}
perorder(root);
cout<<endl;
if(str[i][0]=='*') continue;
else break;
}
}