zoukankan      html  css  js  c++  java
  • 浙大数据结构课后习题 练习三 7-4 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 <iostream>
    #include <queue>
    #include <vector>
    using namespace std;
    /**树结构体*/
    struct tn{
        int index;
        string lc;
        string rc;
    };
    /**层序遍历,返回一个vec*/
    vector<int> levelOrderTreserve(tn tree[],int index){
        vector<int> res;queue<tn> que;tn tmp;
        que.push(tree[index]);
        while(!que.empty()){
            tmp=que.front();
            que.pop();
            if(tmp.lc!="-") que.push(tree[(tmp.lc[0]-'0')]);
            if(tmp.rc!="-") que.push(tree[(tmp.rc[0]-'0')]);
            if(tmp.lc=="-"&&tmp.rc=="-") res.push_back(tmp.index);
        }
        return res;
    }
    int main()
    {
        /**input*/
        int T;
        cin>>T;
        tn tree[T];int judgeRoot[T];int rootPos;
        for(int i=0;i<T;i++) judgeRoot[i]=0;
        for(int i=0;i<T;i++){
            cin>>tree[i].lc>>tree[i].rc;tree[i].index=i;
            /**找出根节点*/
            if(tree[i].lc!="-") judgeRoot[tree[i].lc[0]-'0']++;
            if(tree[i].rc!="-") judgeRoot[tree[i].rc[0]-'0']++;
        }
        for(int i=0;i<T;i++) if(!judgeRoot[i]) rootPos=i;
        vector<int> res=levelOrderTreserve(tree,rootPos);
        for(int i=0;i<res.size();i++) {
            cout<<res[i];
            if(i!=res.size()-1) cout<<" ";
        }
        system("pause");
        return 0;
    }
  • 相关阅读:
    Linux配置YUM源(2020最新最详细)
    Linux系统安装Tomcat9(2020最新最详细)
    Linux系统安装JDK1.8(2020最新最详细)
    框架集项目-登录账户过期,如何回到登录主页!
    C# 以管理员方式运行程序
    C#/STM32 WAV转byte WAV数据格式
    C# base64 转 byte[]
    C# 截取屏幕图像
    emWin 学习笔记 —— 用VS2017打开emWin仿真包
    STM32 时钟配置的坑
  • 原文地址:https://www.cnblogs.com/littlepage/p/11380800.html
Copyright © 2011-2022 走看看