03-树2 List Leaves (25分)

层序遍历

题意:

  找到叶子节点 从上到下 从左到右 输出叶子节点

思路:

  用一个队列来模拟

坑点:

  最后输出格式要注意 最后一个没有空格

#include<cstdio>
#include<queue>

using namespace std;

#define MaxTree 10
#define ElementType char
#define Tree int
#define Null -1

queue<int> q;

struct TreeNode{
    ElementType Element;
    Tree Left;
    Tree Right;
}T1[MaxTree];

Tree BuildTree(struct TreeNode T[]){
    Tree Root = -1;
    int N;
    int check[10];
    char cl,cr;
    scanf("%d\n", &N);
    //printf("N=%d\n", N);
    int i = 0;
    if(N){
        for(i = 0; i < N; ++i) check[i] = 0;
        for(i = 0; i < N; ++i){
            scanf("%c %c\n", &cl, &cr);
            T[i].Element = i;
            if(cl != '-'){
                T[i].Left = cl - '0';
                check[T[i].Left] = 1;
            }else{
                T[i].Left = Null;
            }
            if(cr != '-'){
                T[i].Right = cr - '0';
                check[T[i].Right] = 1;
            }else{
                T[i].Right = Null;
            }
        }
        for(i = 0 ; i < N; ++i){
            if(!check[i]) break;
        }
        Root = i;
    }
    //printf("Root=%d\n", Root);
    //for(i = 0; i < N; ++i)
       // printf("element=%d left=%d right=%d\n", T1[i].Element, T1[i].Left, T1[i].Right);
    return Root;
}

void findLeaf(Tree R){
    int flag = 1;
    if(R == Null)
        return ;
    q.push(R);
    int temp = 0;
    while(!q.empty()){
        //printf("no empty\n");
        temp = q.front();
        if((T1[temp].Left == Null) && (T1[temp].Right == Null)){
            if(flag){
                printf("%d", temp);
                flag = 0;
            }
            else
                printf(" %d", temp);
        }
        if(T1[temp].Left != Null)
            q.push(T1[temp].Left);
        if(T1[temp].Right != Null)
            q.push(T1[temp].Right);
        q.pop();
    }
}

int main(){
    Tree R1;
    R1 = BuildTree(T1);
    findLeaf(R1);
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值