zoukankan      html  css  js  c++  java
  • 【递归】二叉树的深度

    输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

     1 /**
     2  * 二叉树的深度
     3  * 
     4  * @author Administrator
     5  *
     6  */
     7 public class Solution {
     8     public int TreeDepth(TreeNode pRoot) {
     9 
    10         if (null == pRoot) {
    11             return 0;
    12         }
    13 
    14         // 递归求左子树深度
    15         int nLeft = TreeDepth(pRoot.left);
    16 
    17         // 递归求右子树深度
    18         int nRight = TreeDepth(pRoot.right);
    19 
    20         // 当前节点深度是:左右子树中深度较大的值加1
    21         return nLeft > nRight ? (1 + nLeft) : (1 + nRight);
    22     }
    23 }
    24 
    25 class TreeNode {
    26     int val = 0;
    27     TreeNode left = null;
    28     TreeNode right = null;
    29 
    30     public TreeNode(int val) {
    31         this.val = val;
    32     }
    33 };
  • 相关阅读:
    Document
    Document
    Document
    Document
    Document
    Document
    Document
    Document
    C#中的委托是什么
    C# Lambda表达式Contains方法 like
  • 原文地址:https://www.cnblogs.com/jiangyi-uestc/p/5846418.html
Copyright © 2011-2022 走看看