• 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 N (≤) 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
    #include<cstdio>
    #include<queue>
    using namespace std;
    const int maxn = 15;
    struct Node{
        int lchild,rchild;
    }node[maxn];
    int h[maxn],leaf[maxn],num = 0;
    bool isRoot[maxn];
    
    int charToint(char c){
        if(c == '-') return -1;
        else{
            isRoot[c-'0'] = false;
            //printf("isRoot[%d] == %d
    ",c-'0',isRoot[c-'0']);
            return c-'0';
        }
    }
    
    void print(int i){
        if(num == 0){
            printf("%d",i);
            num++;
        }    
        else printf(" %d",i);
    }
    
    void BFS(int root){
        queue<int> q;
        q.push(root);
        while(!q.empty()){
            //printf("1
    ");
            int now = q.front();
            q.pop();
            if(node[now].lchild == -1 && node[now].rchild == -1) print(now);
            if(node[now].lchild != -1) q.push(node[now].lchild);
            if(node[now].rchild != -1) q.push(node[now].rchild);
        }    
    }
    
    int main(){
        int n;
        scanf("%d
    ",&n);
        for(int i = 0; i < n; i++){
            isRoot[i] = true;
        }
        char a,b;
        for(int i = 0; i < n; i++){
            scanf("%c %c",&a,&b);
            getchar();
            int u = charToint(a);
            int v = charToint(b);
            node[i].lchild = u;
            node[i].rchild = v; 
        }
        int root;    
        for(int i = 0; i < n; i++){
            if(isRoot[i] == true) root = i;
        }
        //printf("root == %d
    ",root);
        
        BFS(root);
        return 0;
    }
  • 相关阅读:
    Java项目中读取properties文件,以及六种获取路径的方法
    在eclipse中使用JUnit4,以及使用JUnit4进行单元测试的技巧
    [Evernote]印象笔记使用经验技巧
    使用Word2010发布博客文章
    Win7/8 绿色软件开机启动
    常见笔试题
    排序
    数据库知识归纳(索引)
    数据库知识归纳(事务)
    Redis
  • 原文地址:https://www.cnblogs.com/wanghao-boke/p/10409364.html
Copyright © 2020-2023  润新知