zoukankan      html  css  js  c++  java
  • 剑指Offer-37.二叉树的深度(C++/Java)

    题目:

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

    分析:

    递归求解左右子树的最大值即可,每遍历到一个结点,深度加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);
        }
    }
  • 相关阅读:
    多项式牛顿迭代
    小明A+B
    分拆素数和
    选课时间
    今年暑假不AC
    Lowest Common Multiple Plus
    大小写转换问题(java程序)
    VS 中输入带空格的两个字符串
    整除的尾数
    不要62
  • 原文地址:https://www.cnblogs.com/silentteller/p/12046692.html
Copyright © 2011-2022 走看看