生活的烦恼

#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;
}


总结:二叉树。主要用的就是递归思想,递归。





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值