[LeetCode] #111 二叉树的最小深度

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

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

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

 

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

输出:2

一开始以为,和[LeetCode] #104 二叉树的最大深度差不多,求最大改成求最小就行了

//错误代码
/**
* 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 root == null ? 0 : Math.min(minDepth(root.left), minDepth(root.right)) + 1; } }

提交后发现忽视了 二叉树某节点只有左节点或右节点 的特殊情况,例如[2,null,3,null,4,null,5,null,6]

所以需要单独对 特殊情况 讨论

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

迭代/层次遍历,参考[LeetCode] #104 二叉树的最大深度中的第二种解法

求最大深度时,本质是数有多少层;求最小深度时,我们需要在数多少层的过程中判断该层是否有叶子节点。

class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        Queue<TreeNode> tmpQueue = new LinkedList<>();
        tmpQueue.offer(root);
        int res = 0;
        while (!tmpQueue.isEmpty()) {
            res++;
            for (int i = tmpQueue.size(); i > 0;i--) {
                TreeNode node = tmpQueue.poll();
                if (node.left == null && node.right == null) return res;
                if (node.left != null) tmpQueue.offer(node.left);
                if (node.right != null) tmpQueue.offer(node.right);
            }
        }
        return res;
    }
}

知识点:

总结:特殊情况,单独讨论

posted @ 2021-08-08 23:38  1243741754  阅读(49)  评论(0编辑  收藏  举报