求树的深度(通解)

树的深度求解



 递归方法求深度

         寻找递归的条件:

    解题思路: (1)如果树只有一个结点,则树的深度为1。

             (2)如果根结点只有左子树或者只有右子树,那么这棵树的深度是其根结点的左子树的深度再加1。

          (3)如果根结点既有左子树又有右子树,那么这棵树的深度是左子树深度与右子树深度的最大值再加1。

        

  int GetTreeDepth(BiTree &T)
    {
        if (!T)
        {
            return 0;
        }

        int left = GetTreeDepth(BiTree T->lchild);
        int right =GetTreeDepth(BiTree T->rchild);

        return (left >=right ? left  : right) + 1;
    }

原文地址:https://www.cnblogs.com/mld-code-life/p/10347265.html

时间: 2024-08-04 19:42:02

求树的深度(通解)的相关文章

soj 1034 Forest_求树的深度和宽度

题目链接 题意:给你n个节点,m条边,每条边是有向的,这颗树不能有自环,问这颗树的深度和宽度 思路: 不合法情况 1,入度大于1,即存在两条指向同一顶点的边 2,一条入点和出点都相同的边 3,一条变得入点和出点深度已知,但不符合出点的深度是入点的深度加1 4,点入深度未知但出点深度已知 5,遍历完以后,有顶点未遍历,说明有多个根 树的宽度是指,同一层最多有多少个节点 #include <iostream> #include<cstdio> #include<cstring&g

广度优先搜索求树的深度

#include<iostream> #include<vector> #include<stack> #include<string> #include<queue> #include<algorithm> #include<numeric> using namespace std; class node{ public: int val; node* left; node* right; node():val(0),l

PAT-1021 Deepest Root (25 分) 并查集判断成环和联通+求树的深度

A graph which is connected and acyclic can be considered a tree. The height of the tree depends on the selected root. Now you are supposed to find the root that results in a highest tree. Such a root is called the deepest root. Input Specification: E

LeetCode Maximum Depth of Binary Tree (求树的深度)

题意:给一棵二叉树,求其深度. 思路:递归比较简洁,先求左子树深度,再求右子树深度,比较其结果,返回:max_one+1. 1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 *

hdu 4707 Pet【BFS求树的深度】

Pet                                                          Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 1909    Accepted Submission(s): 924 链接:pid=4707">Click Me ! Problem Description O

计算目录树的深度-基于linq

生成word时,有时用户要求要生成所有级别的目录. 这个时候就需要计算目录树的深度.关于求树的深度,已有很多现成的算法.本文主要介绍一种linq的写法.代码看起来挺简洁的. public static int MenuDepth(List<Menu> menuList, int parentId) {    var children = menuList.Where(p => p.parentId == parentId);    if (children.Count() == 0) 

树的子结构和树的深度

输入两棵二叉树A和B,判断B是不是A的子结构,同时求树的深度. 1 #include<iostream> 2 using namespace std; 3 4 typedef struct node 5 { 6 char data;//结点数据 7 struct node *lchild,*rchild;//二叉树结点类型 8 }BSTree;//二叉树结点类型 9 10 11 void Createb(BSTree **p)//建立二叉树 12 { 13 char ch; 14 cin>

求树的最小深度

/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { private int mins=10000; public int minDepth(TreeNode root) { if(root==null) return

剑指offer38:输入一棵二叉树,求该树的深度

1 题目描述 输入一棵二叉树,求该树的深度.从根结点到叶结点依次经过的结点(含根.叶结点)形成树的一条路径,最长路径的长度为树的深度. 2 思路和方法 深度优先搜索,每次得到左右子树当前最大路径,选择其中较大者并回溯.int len = left>right?left+1:right+1;    // 当前最大路径 3 C++ 核心代码 1 /* 2 struct TreeNode { 3 int val; 4 struct TreeNode *left; 5 struct TreeNode *