zoukankan      html  css  js  c++  java
  • 求二叉树的最大深度和广度

    #include <bits/stdc++.h>
    using namespace std;
    
    struct Node{
        int m;
        int l;
        int r;
    }node[100];
    
    int depth[100];
    
    void first(int k,int d){
        depth[d++]++;
        if(node[k].l != 0)first(node[k].l,d);
        if(node[k].r != 0)first(node[k].r,d);
    }
    
    int main(){
        int n;
        cin >> n;
        for(int i = 1;i <= n;i++){
            cin >> node[i].l >> node[i].r;
            node[i].m = i;
        }
        first(1,1);
        int maxwide = -100;
        for(int i =1;i <= n;i++){
            if(depth[i] > maxwide) maxwide = depth[i];
        }
        cout << maxwide << " ";
        int i;
        for( i = 1;depth[i] != 0;i++) ;
        cout << i-1 ;
        return 0;
    }

    这个depth用的秒

    #include "bits/stdc++.h"
    using namespace std;
    
    int a[1000];
    int b[1000];
    
    int width[100];
    int maxdeep = 0;
    
    void dfsdepth(int i,int depth)
    {
        maxdeep = max(depth,maxdeep);
        width[depth]++;
    //    if(a[i] == 0 && b[i] == 0)
    //        return;
        if(a[i] != 0)
            dfsdepth(a[i],depth+1);  //一开始我用的是depth++,后来意识到递归不能这样,加1以后就是新的depth了
        if(b[i] != 0)
            dfsdepth(b[i],depth+1);  //shift + tab
    }
    
    int main()
    {
        int n;
        int maxwidth = 0;          //if maxwidth is not given a initial number ,the ans will be 3. funny 
        cin >> n;
        for(int i=1;i <= n;i++)
            cin >> a[i] >> b[i];  //left && right can not be the name!!
    
        dfsdepth(1,1);
    
        for(int i=0;i < 100;i++)
            maxwidth = max(maxwidth,width[i]);
    
        cout << maxwidth << " " << maxdeep << endl;
    
        return 0;
    }

    用dfs搜索,啊啊啊啊啊啊啊啊,遇到了n多个bug好气啊,最后还是看答案写出来的,我好菜啊。

  • 相关阅读:
    MySQL数据库基本操作(二)
    MySQL数据库基本操作(一)
    13.常见模块re-正则模块
    12.常见模块time、json模块
    11.迭代器与生成器、模块与包
    10.文件的输入输出、异常
    9.多继承、类的特殊方法、装饰器
    8.类的概念、定义、属性、继承
    7.内置函数、作用域、闭包、递归
    6.函数基础
  • 原文地址:https://www.cnblogs.com/cunyusup/p/7745791.html
Copyright © 2011-2022 走看看