zoukankan      html  css  js  c++  java
  • 03-树2 List Leaves

    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 (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

    用的是层序遍历

     1 #include<iostream>
     2 
     3 #include<vector>
     4 #include<queue>
     5 #include<algorithm>
     6 #define maxsize 10
     7 #define tree int 
     8 #define Null -1
     9 using namespace std;
    10 int tag=1;
    11 struct treenode{
    12 int left;
    13 int right;
    14 }t[maxsize];
    15 tree treebuild(struct treenode t[])
    16 {
    17 int N; cin>>N; vector<int> check(N,0);
    18 char cl,cr;
    19 if(N){ 
    20 for(int i=0;i<N;i++) {
    21 cin>>cl>>cr;
    22 if(cl!='-'){
    23 t[i].left=cl-'0';
    24 check[t[i].left]=1;
    25 }else t[i].left=Null;
    26 if(cr!='-'){
    27 t[i].right=cr-'0';
    28 check[t[i].right]=1;
    29 }else t[i].right=Null;
    30 }
    31 for(int i=0;i<N;i++)
    32 if(check[i]==0) return i;
    33 }   
    34 }
    35 void leafcout(tree r){
    36    // cout<<1;
    37 queue<int> Q; int elem;
    38     if(r==Null) return;
    39     Q.push(r);
    40     while(Q.size()!=0){
    41     elem=Q.front();
    42     Q.pop();
    43     if(t[elem].left==Null&&t[elem].right==Null){
    44     //cout<<2;
    45     if(tag--==1) cout<<elem;
    46     else cout<<" "<<elem;
    47 }
    48 if(t[elem].left!=Null) Q.push(t[elem].left); 
    49 if(t[elem].right!=Null) Q.push(t[elem].right);
    50 } 
    51 }
    52 int main()
    53 {
    54 tree r;
    55 r=treebuild(t);
    56 leafcout(r);
    57 return 0;
    58 }
    View Code
  • 相关阅读:
    C语言常用函数-findfirst()搜索指定磁盘目录里文件函数
    C语言常用函数-getcwd()获取当前工作目录函数
    C语言常用函数目录
    C语言常用函数-_rmdir()建立目录函数
    C语言常用函数-mkdir()建立目录函数
    NX二次开发-UF_DRF_ask_dim_info获得图纸尺寸属于哪个视图和图纸页
    NX二次开发-NXOpenC++属性操作
    VMware虚拟机设置双网卡上网
    FreeCAD二次开发-计算模型是否报错,报错则停止
    NX二次开发-自动将NX标题设置为prt路径
  • 原文地址:https://www.cnblogs.com/A-Little-Nut/p/8056048.html
Copyright © 2011-2022 走看看