码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树的最大深度

时间:2020-05-18 01:09:22      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:return   else   style   com   href   public   math   span   class   

此博客链接:https://www.cnblogs.com/ping2yingshi/p/12907812.html   

二叉树的最大深度(59min)

题目链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],

3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。

题解:

        思路:采用递归思想。

                 1.当树为空时,返回0.

                  2.遍历左子树和右子树,求左子树和右子树中大的值。

       注意:最后返回的是树的最大深度,还需要加上根节点。

class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null)
            return 0;
        else{
        int leftd=maxDepth(root.left);
        int rightd=maxDepth(root.right);
        return Math.max(leftd,rightd)+1;
        }
    }
}

 

二叉树的最大深度

标签:return   else   style   com   href   public   math   span   class   

原文地址:https://www.cnblogs.com/ping2yingshi/p/12907812.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!