题目:

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

分析:

递归求解左右子树的最大值即可,每遍历到一个结点,深度加1,最后返回左右子树中的最大值便是树的深度了。

程序:

C++

class Solution {
public:
    int TreeDepth(TreeNode* pRoot)
    {
        if(pRoot == nullptr)
            return 0;
        return helper(pRoot);
    }
    int helper(TreeNode* pRoot){
        if(pRoot == nullptr)
            return 0;
        return max(helper(pRoot->left)+1, helper(pRoot->right)+1);
    }
};

Java

import java.lang.Math;
public class Solution {
    public int TreeDepth(TreeNode root) {
        if(root == null)
            return 0;
        return helper(root);
        
    }
    public int helper(TreeNode root){
        if(root == null)
            return 0;
        return Math.max(helper(root.left)+1, helper(root.right)+1);
    }
}

相关文章:

  • 2021-12-12
  • 2021-06-25
  • 2021-06-29
  • 2022-02-05
  • 2021-12-13
  • 2021-10-01
  • 2022-12-23
  • 2021-09-22
猜你喜欢
  • 2021-09-17
  • 2021-06-04
  • 2022-01-09
  • 2022-12-23
  • 2022-01-19
相关资源
相似解决方案