LeetCode—111. Minimum Depth of Binary Tree & 104. Maximum Depth of Binary Tree

LeetCode—111. Minimum Depth of Binary Tree & 104. Maximum Depth of Binary Tree

题目

https://leetcode.com/problems/minimum-depth-of-binary-tree/description/
https://leetcode.com/problems/maximum-depth-of-binary-tree/description/
二叉树的最小深度。 以及最大深度
在这里插入图片描述

思路及解法

递归
这道题其实需要想明白有哪几种情况:

  • 父节点为空,深度是0
  • 父节点不为空时,最小深度不一定就是两棵树中较小的深度,有可能一棵树是空的,这时候最小深度就是另一棵树的深度+1
    • 若是两棵子树都不为空,返回较小的深度
    • 若是其中任意一颗为空,返回另一颗(不管这颗是否是空)的深度+1
代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        if(root!=null && root.left!=null && root.right!=null){
            int l = minDepth(root.left);
            int r = minDepth(root.right);
            return (l<r?l:r)+1;
        }else if(root!=null && root.left==null){
            return 1+minDepth(root.right);
        }else if (root!=null && root.right==null){
            return 1+minDepth(root.left);
        }else{
            return 0;
        }
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root!=null && root.left!=null && root.right!=null){
            int l = maxDepth(root.left);
            int r = maxDepth(root.right);
            return (l>r?l:r)+1;
        }else if(root!=null && root.left==null){
            return 1+maxDepth(root.right);
        }else if(root!=null && root.right==null){
            return 1+maxDepth(root.left);
        }else{
            return 0;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值