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

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

    输入:

    第一行一个整数n。

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

    5

    2 3

    4 5

    0 0

    0 0

    0 0

    #include <iostream>
    #include <queue>
    
    using namespace std;
    
    struct{
        int left;
        int right;
    }tree[100];
    
    int get_height(int i)
    {
        if(!i) return 0;
        return 1 + max(get_height(tree[i].left),get_height(tree[i].right));
    }
    
    int get_width(int i)
    {
        if(!i) return 0;
    
        queue<int> q;
        int maxwidth = 1;
        int tmpwidth = 0;
        int tmp;
        int max1 = 0;
        q.push(i);
        while(!q.empty())
        {
            tmpwidth = q.size();
            while(tmpwidth)
            {
                tmp = q.front();
                q.pop();
                tmpwidth--;
                if(tree[tmp].left) q.push(tree[tmp].left);
                if(tree[tmp].right) q.push(tree[tmp].right);
            }
    
            max1 = q.size();
            maxwidth = max(max1,maxwidth);
    
        }
    
        return maxwidth;
    
    }
    int main()
    {
        int n;
        cin >> n;
    
        for(int i = 1; i <= n; i++)
        {
            int a,b;
            cin >> a >> b;
            tree[i].left = a;
            tree[i].right = b;
        }
    
        cout << get_width(1) << " ";
        cout << get_height(1) << endl;
    
    
    
        return 0;
    }
  • 相关阅读:
    Notes of Daily Scrum Meeting(12.22)
    一个合格的程序员应该读过哪些书
    snprintf vs sprintf
    Centos 关闭图形界面
    oracle selinux 问题
    struct 和typedef struct的区别
    c语言字符串函数
    504. Base 7
    汉诺塔python实现
    VIM字符编码基础知识
  • 原文地址:https://www.cnblogs.com/zyqBlog/p/5883117.html
Copyright © 2011-2022 走看看