TGViewer
PHP | LeetCode PHP | LeetCode @easy_php_task · 1.33K subscribers
Post #1045 135
Задача: 1302. Deepest Leaves Sum
Сложность: medium

Дано корень бинарного дерева, вернуть сумму значений его самых глубоких листьев.

Пример:
Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
Output: 15


👨‍💻 Алгоритм:

1⃣Поместите корень в стек.

2⃣Пока стек не пуст. Извлеките узел из стека и обновите текущее число. Если узел является листом, обновите сумму самых глубоких листьев deepest_sum. Поместите правый и левый дочерние узлы в стек.

3⃣Верните deepest_sum.

😎 Решение:
class Solution {
function deepestLeavesSum($root) {
$deepestSum = 0;
$depth = 0;
$stack = [[$root, 0]];

while (!empty($stack)) {
list($node, $currDepth) = array_pop($stack);

if ($node->left === null && $node->right === null) {
if ($depth < $currDepth) {
$deepestSum = $node->val;
$depth = $currDepth;
} elseif ($depth == $currDepth) {
$deepestSum += $node->val;
}
} else {
if ($node->right !== null) {
$stack[] = [$node->right, $currDepth + 1];
}
if ($node->left !== null) {
$stack[] = [$node->left, $currDepth + 1];
}
}
}
return $deepestSum;
}
}


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_php_task
  1. Oct 15, 2026Задача: 474. Ones and Zeroes Сложность: medium Дан массив двоичных строк strs и два целых…
  2. Oct 15, 2026Задача: 1273. Delete Tree Nodes Сложность: medium Дерево, укорененное в узле 0, задано сле…
  3. Oct 14, 2026Задача: 724. Find Pivot Index Сложность: easy Если задан массив целых чисел nums, вычислит…
  4. Oct 14, 2026Задача: 674. Longest Continuous Increasing Subsequence Сложность: easy Дан неотсортированн…
  5. Oct 13, 2026Задача: 899. Orderly Queue Сложность: hard Вам дана строка s и целое число k. Вы можете вы…
  6. Oct 11, 2026Задача: 913. Cat and Mouse4 Сложность: hard В игру на неориентированном графе играют два и…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →