111. Minimum Depth of Binary Tree
leetcode easy
Task
Дано бинарное дерево, найдите его минимальную глубину.
Минимальная глубина - это количество узлов вдоль самого короткого пути от корневого узла до ближайшего листового узла.
Пример:
Input: root = [3,9,20,null,null,15,7]
Output: 2
C# solution
matched/originalpublic 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++ solution
auto-draft, review before submit#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 solution
matched/originalclass 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 solution
matched/originalvar 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 solution
matched/originalclass 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 solution
matched/originalfunc 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)
}Explanation
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)).
😎