104. Maximum Depth of Binary Tree

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

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

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

Пример:

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

Output: 3

C# решение

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

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:
    public int MaxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        } else {
            int left_height = MaxDepth(root.left);
            int right_height = MaxDepth(root.right);
            return 1 + max(left_height, right_height);
        }
    }
}

Java решение

сопоставлено/оригинал
class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        } else {
            int left_height = maxDepth(root.left);
            int right_height = maxDepth(root.right);
            return java.lang.Math.max(left_height, right_height) + 1;
        }
    }
}

JavaScript решение

сопоставлено/оригинал
var maxDepth = function (root) {
    if (root === null) {
        return 0;
    }
    const left_height = maxDepth(root.left);
    const right_height = maxDepth(root.right);
    return 1 + Math.max(left_height, right_height);
};

Python решение

сопоставлено/оригинал
class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if root is None:
            return 0
        else:
            left_height = self.maxDepth(root.left)
            right_height = self.maxDepth(root.right)
            return max(left_height, right_height) + 1

Go решение

сопоставлено/оригинал
func maxDepth(root *TreeNode) int {
    if root == nil {
        return 0
    }
    left_height := maxDepth(root.Left)
    right_height := maxDepth(root.Right)
    return 1 + max(left_height, right_height)
}

func max(a int, b int) int {
    if a > b {
        return a
    }
    return b
}

Algorithm

1️⃣

Можно обойти дерево, используя стратегию поиска в глубину (DFS) или поиска в ширину (BFS).

2️⃣

Для данной задачи подойдет несколько способов.

3️⃣

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

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

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