首页 > 解决方案 > 找到二叉树的最小深度

问题描述

我需要找到二叉树的最小深度。我的代码在这个测试用例上失败了:[-9, -3, 2, null, 4, 4, 0, -6, null, -5].

给定一棵二叉树,求其最小深度示例:

给定二叉树[3, 9, 20, null, null, 15, 7]

    3
   / \
  9  20
    /  \
   15   7

返回其最小深度 = 2。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    public int count(TreeNode root) { 
        if (root == null) {
            return 0;
        }

        return 1 + Math.max(count(root.left), count(root.right));
    }

    public int minDepth(TreeNode root) {
        int left = 0, right = 0;

        if (root == null) {
            return 0;
        }

        if (root.right == null) {
           return  1 + count(root.left);
        }      

        if (root.left == null) {
            return  1 + count(root.right);
        }

        left = count(root.left);
        right = count(root.right);

        return  1 + Math.min(left, right);
    }
}

标签: javabinary-tree

解决方案


我相信问题在于使用 Math.max 而不是 Math.min

public int minDepth(TreeNode root)
{

    if(root == null)
        return 0;

    return 1 + Math.min(minDepth(root.left), minDepth(root.right));
}

推荐阅读