111. Minimum Depth of Binary Tree

LeetCode easy оригинал: C# #csharp #easy #graph #leetcode #math #recursion #tree #two-pointers

Дано бинарное дерево, найдите его минимальную глубину.

Минимальная глубина - это количество узлов вдоль самого короткого пути от корневого узла до ближайшего листового узла.

Пример:

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

Output: 2

C# решение

сопоставлено/оригинал
public class Solution {
    private int Dfs(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null) {
            return 1 + Dfs(root.right);
        } else if (root.right == null) {
            return 1 + Dfs(root.left);
        }
        return 1 + Math.Min(Dfs(root.left), Dfs(root.right));
    }
    public int MinDepth(TreeNode root) {
        return Dfs(root);
    }
}

C++ решение

auto-draft, проверить перед отправкой
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    private int Dfs(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null) {
            return 1 + Dfs(root.right);
        } else if (root.right == null) {
            return 1 + Dfs(root.left);
        }
        return 1 + min(Dfs(root.left), Dfs(root.right));
    }
    public int MinDepth(TreeNode root) {
        return Dfs(root);
    }
}

Java решение

сопоставлено/оригинал
class Solution {
    private int dfs(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null) {
            return 1 + dfs(root.right);
        } else if (root.right == null) {
            return 1 + dfs(root.left);
        }
        return 1 + Math.min(dfs(root.left), dfs(root.right));
    }

    public int minDepth(TreeNode root) {
        return dfs(root);
    }
}

JavaScript решение

сопоставлено/оригинал
var minDepth = function (root) {
    function dfs(root) {
        if (root === null) {
            return 0;
        }
        if (root.left === null) {
            return 1 + dfs(root.right);
        } else if (root.right === null) {
            return 1 + dfs(root.left);
        }
        return 1 + Math.min(dfs(root.left), dfs(root.right));
    }
    return dfs(root);
};

Python решение

сопоставлено/оригинал
class Solution:
    def minDepth(self, root):
        def dfs(root):
            if root is None:
                return 0
            if root.left is None:
                return 1 + dfs(root.right)
            elif root.right is None:
                return 1 + dfs(root.left)
            return 1 + min(dfs(root.left), dfs(root.right))

        return dfs(root)

Go решение

сопоставлено/оригинал
func minDepth(root *TreeNode) int {
    var dfs func(root *TreeNode) int
    dfs = func(root *TreeNode) int {
        if root == nil {
            return 0
        }
        if root.Left == nil {
            return 1 + dfs(root.Right)
        } else if root.Right == nil {
            return 1 + dfs(root.Left)
        }
        leftDepth := dfs(root.Left)
        rightDepth := dfs(root.Right)
        if leftDepth < rightDepth {
            return 1 + leftDepth
        } else {
            return 1 + rightDepth
        }
    }
    return dfs(root)
}

Algorithm

1️⃣

Мы будем использовать метод обхода в глубину (dfs) с корнем в качестве аргумента.

Базовое условие рекурсии: это для узла NULL, в этом случае мы должны вернуть 0.

2️⃣

Если левый ребенок корня является NULL: тогда мы должны вернуть 1 + минимальную глубину для правого ребенка корневого узла, что равно 1 + dfs(root.right).

3️⃣

Если правый ребенок корня является NULL: тогда мы должны вернуть 1 + минимальную глубину для левого ребенка корневого узла, что равно 1 + dfs(root.left). Если оба ребенка не являются NULL, тогда вернуть 1 + min(dfs(root.left), dfs(root.right)).

😎

Вакансии для этой задачи

Показаны активные вакансии с пересечением по тегам задачи.

Все вакансии
Активных вакансий пока нет.