资讯专栏INFORMATION COLUMN

[Leetcode-Tree]Maximum / Minimum Depth of Binary T

Thanatos / 436人阅读

摘要:解题思路用递归实现很简单,对于每个根节点,最大深度就等于左子树的最大深度和右子树的最大深度的较大值。解题思路本题的注意点在于如果某个根节点有一边的子树为空,那么它的深度就等于另一边不为空的子树的深度,其他的逻辑与上一题相同。

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.

1.解题思路

用递归实现很简单,对于每个根节点,最大深度就等于左子树的最大深度和右子树的最大深度的较大值。

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

Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

1.解题思路

本题的注意点在于如果某个根节点有一边的子树为空,那么它的深度就等于另一边不为空的子树的深度,其他的逻辑与上一题相同。

2.代码

public class Solution {
    public int minDepth(TreeNode root) {
        if(root==null) return 0;
        if(root.left==null&&root.right!=null) 
            return minDepth(root.right)+1;
        if(root.right==null&&root.left!=null)
            return minDepth(root.left)+1;
        int leftmin=minDepth(root.left);
        int rightmin=minDepth(root.right);
        return Math.min(leftmin,rightmin)+1;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/69809.html

相关文章

  • [Leetcode] Maximum and Minimum Depth of Binary Tre

    摘要:递归法复杂度时间空间递归栈空间思路简单的递归。该递归的实质是深度优先搜索。这里我们还有改进的余地,就是用迭代加深的有限深度优先搜索。 Maximum Depth of Binary Tree Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the l...

    boredream 评论0 收藏0
  • [Leetcode-Tree]Binary Tree Maximum Path Sum

    摘要:但是本题的难点在于,使用递归实现,但是前面的第四种情况不能作为递归函数的返回值,所以我们需要定义两个值,代表单边路径的最大值,用于递归用于和回路的较大值。 Binary Tree Maximum Path SumGiven a binary tree, find the maximum path sum. For this problem, a path is defined as a...

    caige 评论0 收藏0
  • Leetcode PHP题解--D41 104. Maximum Depth of Binary T

    摘要:题目链接题目分析返回给定的二叉树有多少层。思路每下一级,层树,并记录到类属性中。并判断是否大于已知最深层树。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 104. Maximum Depth of Binary Tree 题目链接 104. Maximum Depth of Binary Tree 题目分析 返回给定的二叉树有多少层。 思路 每下一级,层树+1,并记录到类属性lev...

    LMou 评论0 收藏0
  • 前端 | 每天一个 LeetCode

    摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: showImg(htt...

    张汉庆 评论0 收藏0
  • LeetCode 攻略 - 2019 年 7 月下半月汇总(100 题攻略)

    摘要:月下半旬攻略道题,目前已攻略题。目前简单难度攻略已经到题,所以后面会调整自己,在刷算法与数据结构的同时,攻略中等难度的题目。 Create by jsliang on 2019-07-30 16:15:37 Recently revised in 2019-07-30 17:04:20 7 月下半旬攻略 45 道题,目前已攻略 100 题。 一 目录 不折腾的前端,和咸鱼有什么区别...

    tain335 评论0 收藏0

发表评论

0条评论

Thanatos

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<