#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
typedef struct node{
char data;
node *left,*right;
}node;
char x;
int level,count,num; //这几个变量需要定义成全局的
node *ctree()
{
getchar();
node *p=(node*)malloc(sizeof(node));
cin>>x;
if(x=='#')
p=NULL;
//else if(x=='@')
//return p;
else{
p->data=x;
p->left=ctree();
p->right=ctree();
}
return p;
}
void bianLi(node *p)
{
//如果找到了相等的层数,就输出;如果不相等就一直递归找
if(count==level){
//printf("第%d次调用输出",num);
if(num==1)
cout<<p->data;
if(num!=1)
cout<<"~"<<p->data;
num++;
}
if(p->left!=NULL){
count++;
bianLi(p->left);
count--; //因为count是全局变量,所以当count++并且函数递归结束后,要回到上一层就--
}
if(p->right!=NULL){
count++;
bianLi(p->right);
count--;
}
}
int main()
{
//freopen("二叉树.txt","r",stdin);
int n;
//int i,j; //q数组的下标,q数组的下标
//node *q[1000];
cin>>n;
while(n--){
num=1; //为了处理那个波浪线,加的一个标记
count=1; //记录调用的第几层
node *t=ctree(); //递归建立二叉树
getchar(); //吸收掉@
getchar(); //吸收掉@带来的空格
cin>>level; //需要输出的层
bianLi(t); //递归层次遍历
cout<<endl;
/* //使用队列层次遍历,只不过是每一层都输出了
if(t!=NULL){
i=1;
j=2;
q[i]=t;
}
while(i!=j){
t=q[i];
if(i==level)
cout<<t->data<<"~";
if(t->left!=NULL){
q[j]=t->left;
j++;
}
if(t->right!=NULL){
q[j]=t->right;
j++;
}
i++;
}
cout<<endl;
*/
}
return 0;
}
总结:二叉树。主要用的就是递归思想,递归。