请根据题目实际情况选择函数调用
#include <bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
typedef struct node{///结构体
char data;
node *l,*r;
}tree ;
char shu[55];///有','的输入数组
int q,cnt,sum;
tree *creat(char *xian,char *zhong,int len){///先序中序建二叉树
tree *t=new tree;
if(len<=0)return NULL;
t->data=*xian;
char *p;
for(p=zhong;p<zhong+len;p++)
if(*p==*xian)break;
int k=p-zhong;
t->l=creat(xian+1,zhong,k);
t->r=creat(xian+k+1,p+1,len-k-1);
return t;
}
tree *rcreat(char *zhong,char *hou,int len){///中序后序建二叉树
tree *t=new tree;
if(len<=0)return NULL;
t->data=*(hou+len-1);
char *p;
for(p=zhong;p<zhong+len;p++)
if(*p==*(hou+len-1))break;
int k=p-zhong;
t->l=rcreat(zhong,hou,k);
t->r=rcreat(zhong+k+1,hou+k,len-k-1);
return t;
}
tree *_creat(tree *t){///带','建二叉树
t=new tree;
char x=shu[q++];
if(x==',')t=NULL;
else {
t->data=x;
t->l=_creat(t->l);
t->r=_creat(t->r);
}
return t;
}
void xianxu(tree *t){///先序遍历
if(t){
cout<<t->data;
xianxu(t->l);
xianxu(t->r);
}
}
void zhongxu(tree *t){///中序遍历
if(t){
zhongxu(t->l);
cout<<t->data;
zhongxu(t->r);
}
}
void houxu(tree *t){///后序遍历
if(t){
houxu(t->l);
houxu(t->r);
cout<<t->data;
}
}
void bfs(tree *t){///层次遍历
queue<node *>q;
q.push(t);
while(!q.empty()){
node *temp=q.front();
q.pop();
if(temp){
q.push(temp->l);
q.push(temp->r);
cout<<temp->data;
}
}
}
int yezi(tree *t){///带','的叶子节点个数
if(t){
if(t->l==NULL&&t->r==NULL)
cnt++;
yezi(t->l);
yezi(t->r);
}
return cnt;
}
int _yezi(tree *t){///叶子节点输出
queue<tree *>q;
q.push(t);
while(!q.empty()){
t=q.front();
q.pop();
if(t){
if(t->l==NULL&&t->r==NULL)
cout<<t->data;
q.push(t->l);
q.push(t->r);
}
}
}
int shendu(tree *t){///树深度计算
if(t){
int r=shendu(t->r)+1;
int l=shendu(t->l)+1;
return max(r,l);
}
return 0;
}
int main(){///主函数
ios::sync_with_stdio(0);///防止超时,可忽略
char xian[55],zhong[55],hou[55];
int t;
cin>>t;
while(t--){
cin>>zhong>>hou;
while(cin>>shu){
cnt=0,q=0,sum=0;
tree *t=new tree;
t=_creat(t);
_yezi(t);
cout<<endl;
}
}
return 0;
}
|