力扣每日一题day33[111. 二叉树的最小深度]

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

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

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

示例 1:

输入:root = [3,9,20,null,null,15,7]
输出:2

示例 2:

输入:root = [2,null,3,null,4,null,5,null,6]
输出:5

本题依然是前序遍历和后序遍历都可以,前序求的是深度,后序求的是高度。

  • 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)

  • 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数后者节点数(取决于高度从0开始还是从1开始)

用后序遍历,其实求的是根节点到叶子节点的最小距离,就是求高度的过程,不过这个最小距离 也同样是最小深度。

递归法

来来来,一起递归三部曲:

  1. 确定递归函数的参数和返回值

参数为要传入的二叉树根节点,返回的是int类型的深度。

代码如下:

int getMinDepth(TreeNode root)

确定终止条件

终止条件也是遇到空节点返回0,表示当前节点的高度为0。

代码如下:

if(root==null) return 0;

确定单层递归的逻辑

如果左子树为空,右子树不为空,说明最小深度是 1 + 右子树的深度。

右子树为空,左子树不为空,最小深度是 1 + 左子树的深度。 最后如果左右子树都不为空,返回左右子树深度最小值 + 1 。

int leftDepth=getMinDepth(root.left);
int rightDepth=getMinDepth(root.right);
​
if(root.left==null&&root.right!=null){
    return 1+rightDepth;
}
if(root.left!=null&&root.right==null){
    return 1+leftDepth;
}
return 1+Math.min(leftDepth,rightDepth);
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        return getMinDepth(root);
    }
    int getMinDepth(TreeNode root){
        if(root==null) return 0;
​
        int leftDepth=getMinDepth(root.left);
        int rightDepth=getMinDepth(root.right);
​
        if(root.left==null&&root.right!=null){
            return 1+rightDepth;
        }
        if(root.left!=null&&root.right==null){
            return 1+leftDepth;
        }
        return 1+Math.min(leftDepth,rightDepth);
    }
}

迭代法

只有当左右都为空的时候,才说明遍历的最低点了。如果其中一个为空则不是最低点

代码:

class Solution {
    public int minDepth(TreeNode root) {
        if(root==null) return 0;
        int depth=0;
        Queue<TreeNode> queue=new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            int size=queue.size();
            depth++;
            for(int i=0;i<size;i++){
                TreeNode cur=queue.poll();
                if(cur.left!=null) queue.add(cur.left);
                if(cur.right!=null) queue.add(cur.right);
                if(cur.left==null&&cur.right==null) return depth;
            }
        }
        return depth;
    }
}

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值