​LeetCode刷题实战104:二叉树的最大深度

程序IT圈

共 998字,需浏览 2分钟

 ·

2020-11-23 21:23

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 二叉树的最大深度,我们先来看题面:

https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

Given a binary tree, find its maximum depth.


The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.


Note: A leaf is a node with no children.

题意


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

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

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

样例

解题


这道题比较简单。我们直接用递归代码就可以解决了。 递归的结束条件: 当节点为叶子节点的时候. 递归的子问题: 当前最大深度 = 左右子树最大深度的较大者 + 1

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


好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力。


上期推文:

LeetCode1-100题汇总,希望对你有点帮助!
LeetCode刷题实战101:对称二叉树
LeetCode刷题实战102:二叉树的层序遍历
LeetCode刷题实战103:二叉树的锯齿形层次遍历

浏览 4
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报