0
点赞
收藏
分享

微信扫一扫

POJ 1577 Falling Leaves(二叉搜索树)


​​传送门​​

题目大意

构造一棵树,输出其先序遍历。
根据字母表顺序,左子树上的任意结点字母都在根结点前面,而右子树上的任意结点字母都在根结点后面。其中输入数据很独特,首行把二叉树的所有叶子结点列出来组成一个字符串,然后从去掉叶子结点后所形成的新二叉树中再找叶子结点,再组成一个字符串,依次进行下去,直到剩下一个根结点为止。

思路

可以把输入数据保存在一个二维字符数组里面,然后建立一个结构体储存二叉树的结点与左右孩子信息。

代码

struct node{
char val;
int l;
int r;
}tree[50];

char str[100][100];
int tot;

void init(int tot){
tree[tot].l=tree[tot].r=-1;
}

void build(int root,char val){
if(tree[root].l!=-1&&tree[root].val>val){
build(tree[root].l,val);
}
else if(tree[root].r!=-1&&tree[root].val<val){
build(tree[root].r,val);
}
else{
init(tot);
tree[tot].val=val;
if(val<tree[root].val) tree[root].l=tot;
else tree[root].r=tot;
tot++;
}
}

void print(int root){
if(tree[root].val)
cout<<tree[root].val;
if(tree[root].l) print(tree[root].l);
if(tree[root].r) print(tree[root].r);
}


int main(){
while(cin>>str[0]){
int count=0;
if(str[0][0]=='$') break;
while(str[count][0]>='A'&&str[count][0]<='Z'){
cin>>str[++count];
}
//cout<<count<<endl;
count--;
memset(tree,0,sizeof tree);
tot=1;
init(tot);
tree[tot].val=str[count][0];
tot++;
for(int i=count-1;i>=0;i--){
for(int j=0;j<strlen(str[i]);j++){
build(1,str[i][j]);
}
}
print(1);
puts("");
}
}


举报

相关推荐

0 条评论