zoukankan      html  css  js  c++  java
  • 16.二叉树最大宽度和高度

     时间限制: 1 s

     空间限制: 128000 KB

     题目等级 : 白银 Silver

    题解

     查看运行结果

    题目描述 Description

        给出一个二叉树,输出它的最大宽度和高度。

    输入描述 Input Description

    第一行一个整数n

    下面n行每行有两个数,对于第i行的两个数,代表编号为i的节点所连接的两个左右儿子的编号。如果没有某个儿子为空,则为0

    输出描述 Output Description

    输出共一行,输出二叉树的最大宽度和高度,用一个空格隔开。

    样例输入 Sample Input

    5

    2 3

    4 5

    0 0

    0 0

    0 0

    样例输出 Sample Output

    2 3

    数据范围及提示 Data Size & Hint

    n<16

    默认第一个是根节点

    以输入的次序为编号

    2-N+1行指的是这个节点的左孩子和右孩子

    注意:第二题有极端数据!

              1

              0 0

    这题你们别想投机取巧了,给我老老实实搜索!

    代码:

    #include

    using namespace std;

    #include

    #include

    int a[20][3],w[20],h[20],h1;

    int cmp(const int &a,const int &b)

    {

           if(a>b) return 1;

           return 0;

    }

    int main()

    {

           int n;

           scanf("%d",&n);

           for(int i=1;i<=n;++i)

           scanf("%d%d",&a[i][1],&a[i][2]);//a储存i的左右孩子

           h[1]=1;

           for(int i=1;i<=n;++i)

        {

               if(a[i][1]!=0)

               h[a[i][1]]=h[i]+1;//i所在的高度储存下来

               if(a[i][2]!=0)

               h[a[i][2]]=h[i]+1;

           }

           for(int i=1;i<=n;++i)

           w[h[i]]++;//把每个高度的宽储存下来

           sort(h+1,h+n+1,cmp);//取宽度和高度最大的输出

           sort(w+1,w+n+1,cmp); 

           printf("%d %d",w[1],h[1]);

          

           return 0;

    }

  • 相关阅读:
    POJ 3140 Contestants Division (树dp)
    POJ 3107 Godfather (树重心)
    POJ 1655 Balancing Act (树的重心)
    HDU 3534 Tree (经典树形dp)
    HDU 1561 The more, The Better (树形dp)
    HDU 1011 Starship Troopers (树dp)
    Light oj 1085
    Light oj 1013
    Light oj 1134
    FZU 2224 An exciting GCD problem(GCD种类预处理+树状数组维护)同hdu5869
  • 原文地址:https://www.cnblogs.com/c1299401227/p/5370807.html
Copyright © 2011-2022 走看看