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;
    }

  • 相关阅读:
    asp.net 启动关闭iis
    vue 界面关闭触发事件 ---实例销毁之前调用
    ElmentUI 设置禁止点击遮罩关闭 el-dialog 弹窗
    C#反射
    SQL Server 创建游标(cursor)
    文件解压缩
    文件流操作
    Linq查询
    C#线程 多线程 进程
    匿名类型和反射
  • 原文地址:https://www.cnblogs.com/eason9906/p/11755140.html
Copyright © 2011-2022 走看看