MOOC

03-树2 List Leaves (25分)

Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.
Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer NNN (≤10\le 10≤10) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N−1N-1N−1. Then NNN lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a "-" will be put at the position. Any pair of children are separated by a space.
Output Specification:

For each test case, print in one line all the leaves' indices in the order of top down, and left to right. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.

思路:与上一题一样的建树,采用静态链表的方式,然后层序遍历即可

#include <stdio.h>
#include <stdlib.h>
#define MaxSize 10
#define Tree int
#define Null -1

struct TreeNode{
    int Left,Right;
}T[MaxSize];

//create tree ,return root
Tree BuildTree(T[])
{
    int n;
    scanf("%d\n",&n);
    int check[MaxSize];
    for(int i=0;i<MaxSize;i++) check[i]=0;
    for(int i=0;i<n;i++){
        char a,b;
        scanf("%c %c\n",&a,&b);
        if(a!='-'){
            T[i].Left=a-'0';
            check[T[i].Left]=1;
        }
        else{
            T[i].Left=Null;
        }
        if(b!='-'){
            T[i].Right=b-'0';
            check[T[i].Right]=1;
        }
        else{
            T[i].Right=Null;
        }
    }
    int i=-1;
    for(i=0;i<n;i++){
        if(!check[i]) break;
    }
    return i;
}

void LevelLeaf(Tree root)
{
    int flag=0;
    int queue[MaxSize];
    int front=0,rear=0;//front point temp,rear point next;
    queue[rear++]=root;
    while(front<rear){
        Tree temp=queue[front++];
        if(T[temp].Left==Null && T[temp].Right == Null){
            if(flag==0) flag=1;
            else printf(" ");
            printf("%d",temp);
        }
        if(T[temp].Left!=Null) queue[rear++]=T[temp].Left;
        if(T[temp].Right!=Null) queue[rear++]=T[temp].Right;
    }
}

int main()
{
    freopen("in.txt","r",stdin);
    Tree root=BuildTree(T);
    LevelLeaf(root);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 作者:王雪聪 你会遇到一个什么样的姑娘? 她多愁伤感还是风情妩媚。 她会有丁香的芬芳, 还是牡丹的绽放? ...
    王雪聪阅读 355评论 5 5
  • 它从黑暗中无声无息地走来 带着青色的微茫 身边燃烧的紫蓝的火焰 也无法驱除让人颤抖的夜寒 一双镇定,冷漠,倔强,骄...
    庭安和兔子阅读 345评论 0 0
  • (一)飞机加火车的千里迢迢 启程的票早已准备好,少年的心已经澎湃。我们来自江南塞北,大河上下,缘聚于二月的邕城,君...
    逗霸君阅读 507评论 6 7

友情链接更多精彩内容