zoukankan      html  css  js  c++  java
  • 求二叉树的深度及每一个节点的深度

    思路:用dfs的方法求,节点的儿子若就是该节点的拓展方向。然后所有的叶子节点中,深度最大的叶子节点的深度就代表了这棵
    二叉树的深度。


    #include<stdio.h>
    #include<iostream>
    #include<stdlib.h>
    using namespace std;
    struct node
    {
        char v;
        int num;
        int depth;
        struct node*ls,*rs;
    };
    int ans=-0x3f3f3f3f;
    char mb;
    struct node*head;
    struct node*build()//
    {
        char ch;
        cin>>ch;
        if(ch=='#') return NULL;
        struct node*p=(struct node*)malloc(sizeof(struct node));
        p->v=ch;
        p->ls=build();
        p->rs=build();
        return p;
    
    };
    
    
    void getdepth(struct node*p,int depth)
    {
        if(!p) return ;
        p->depth=depth;
        if(p->ls==NULL&&p->rs==NULL) ans=max(ans,p->depth);
        getdepth(p->ls,depth+1);
        getdepth(p->rs,depth+1);
    
    }
    void middle(struct node*p)
    {
        if(!p) return ;
        middle(p->ls);
        cout<<"/节点的值:"<<p->v<<"  深度:"<<p->depth<<endl;
        middle(p->rs);
    }
    
    int main()
    {
    
    
    
        head=build();
        getdepth(head,1);
        middle(head);
        cout<<"/树的深度:"<<ans<<endl;
        return 0;
    }

  • 相关阅读:
    discuz制作
    Cookie和Session专题
    ecmall二次开发 直接实例化mysql对象
    ecmall widgets 挂件开发详解
    都是iconv惹的祸
    discuz+ecmall+phpcms整合
    replace into
    权限管理设计二
    权限管理设计一
    SVN服务器搭建和使用(二)
  • 原文地址:https://www.cnblogs.com/eason9906/p/11755140.html
Copyright © 2011-2022 走看看