leetcode 111. 二叉树的最小深度

题目

leetcode 111. 二叉树的最小深度_第1张图片

思路

递归解法,思路直接看注释吧~

注意对于最小深度定义,有一个小坑,下面这棵树的结果应该是2,而不是1,为此我专门加了一个判断:
如果根部只有一个孩子,则另一侧深度恒为1。此时,应取有孩子的那一侧的深度!
leetcode 111. 二叉树的最小深度_第2张图片

题解

// Definition for a binary tree node.
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}


class Solution {
    public int minDepth(TreeNode root) {
        if (root != null) {
            if (root.left == null || root.right == null) {//根部只有一个孩子,则另一侧深度恒为1。此时应取有孩子一侧的深度
                return Math.max(getMinDepth(root.left, 1), getMinDepth(root.right, 1));
            } else {//根部有两个孩子,取两侧最小深度即可
                return Math.min(getMinDepth(root.left, 1), getMinDepth(root.right, 1));
            }
        } else
            return 0;
    }

    public int getMinDepth(TreeNode node, int dep) {
        if (node != null) {
            if (node.left != null && node.right != null) {//有两个孩子,取较小深度
                return Math.min(getMinDepth(node.left, dep + 1), getMinDepth(node.right, dep + 1));
            } else if (node.left != null || node.right != null) { //只有一个孩子,取较大深度
                return Math.max(getMinDepth(node.left, dep + 1), getMinDepth(node.right, dep + 1));
            } else {//没有孩子,则是叶子节点
                return dep + 1;
            }
        } else return dep;
    }
}

前两次提交被坑了
leetcode 111. 二叉树的最小深度_第3张图片

你可能感兴趣的:(leetcode)