Найти минимальную глубину бинарного дерева - PullRequest
0 голосов
/ 11 июля 2019

Мне нужно найти минимальную глубину бинарного дерева. Мой код не пройден в этом тестовом случае: [-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);
    }
}
  • выход = 4
  • ожидается = 3

1 Ответ

0 голосов
/ 11 июля 2019

Я считаю, что проблема в использовании Math.max вместо Math.min

public int minDepth(TreeNode root)
{

    if(root == null)
        return 0;

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