zoukankan      html  css  js  c++  java
  • 7-8 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 N (10) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N1. Then N 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.

    Sample Input:

    8
    1 -
    - -
    0 -
    2 7
    - -
    - -
    5 -
    4 6
    

    Sample Output:

    4 1 5
    

    用了个结构体,因为结点是确定的,只需要根据数据建立树,找到没有parent结点的作为根,然后层序遍历找叶子。

    代码:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct Tree
    {
        int f,l,r;
    }s[10];
    int n;
    void ListLeave(int k)
    {
        int flag = 0;
        int a[20];
        int head = 0,tail = 0;
        a[tail ++] = k;
        while(head < tail)
        {
            if(s[a[head]].l != -1)a[tail ++] = s[a[head]].l;
            if(s[a[head]].r != -1)a[tail ++] = s[a[head]].r;
            if(s[a[head]].l == s[a[head]].r)
            {
                if(flag)printf(" %d",a[head]);
                else printf("%d",a[head]);
                flag ++;
            }
            head ++;
        }
    }
    int main()
    {
        char a,b;
        scanf("%d",&n);
        for(int i = 0;i < n;i ++)
            s[i].f = -1;
        for(int i = 0;i < n;i ++)
        {
            getchar();
            scanf("%c %c",&a,&b);
            if(a!='-')
            {
                s[i].l = a - '0';
                s[a - '0'].f = i;
            }
            else s[i].l = -1;
            if(b!='-')
            {
                s[i].r = b - '0';
                s[b - '0'].f = i;
            }
            else s[i].r = -1;
        }
        for(int i = 0;i < n;i ++)
        {
            if(s[i].f == -1)ListLeave(i);
        }
    }
  • 相关阅读:
    【go语言学习】标准库之time
    【go语言学习】文件操作file
    【go语言学习】反射reflect
    【go语言学习】通道channel
    soap添加
    ubuntu apache 启用gzip
    git 版本回退
    ubuntu打开crontab日志及不执行常见原因
    Ionic3 怎么打开第三方 app,最简单粗暴的方法
    Windows安装使用Openssl创建pks p12证书
  • 原文地址:https://www.cnblogs.com/8023spz/p/7748203.html
Copyright © 2011-2022 走看看