TGViewer
PHP | LeetCode PHP | LeetCode @easy_php_task · 1.33K subscribers
Post #892 160
Задача: 366. Find Leaves of Binary Tree
Сложность: medium

Дан корень бинарного дерева, соберите узлы дерева следующим образом:
Соберите все листовые узлы.
Удалите все листовые узлы.
Повторяйте, пока дерево не станет пустым.

Пример:
Input: root = [1,2,3,4,5]
Output: [[4,5,3],[2],[1]]
Explanation:
[[3,5,4],[2],[1]] and [[3,4,5],[2],[1]] are also considered correct answers since per each level it does not matter the order on which elements are returned.


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

1⃣Реализовать функцию getHeight(node), которая будет вычислять высоту каждого узла в дереве с использованием рекурсивного обхода в глубину (post-order). Если узел является null, вернуть -1.

2⃣Сохранить пары (высота, значение) для всех узлов и отсортировать их по высоте.

3⃣Организовать узлы по высоте и вернуть результат.

😎 Решение:
class Solution {
private $pairs = [];

private function getHeight($node) {
if ($node === null) return -1;
$leftHeight = $this->getHeight($node->left);
$rightHeight = $this->getHeight($node->right);
$currHeight = max($leftHeight, $rightHeight) + 1;
$this->pairs[] = [$currHeight, $node->val];
return $currHeight;
}

public function findLeaves($root) {
$this->getHeight($root);
usort($this->pairs, function($a, $b) {
return $a[0] <=> $b[0];
});
$solution = [];
$currentHeight = -1;
foreach ($this->pairs as $pair) {
if ($pair[0] !== $currentHeight) {
$solution[] = [];
$currentHeight = $pair[0];
}
$solution[count($solution) - 1][] = $pair[1];
}
return $solution;
}
}


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_php_task
  1. Oct 16, 2026Задача: 760. Find Anagram Mappings Сложность: easy Вам даны два целочисленных массива nums…
  2. Oct 15, 2026Задача: 474. Ones and Zeroes Сложность: medium Дан массив двоичных строк strs и два целых…
  3. Oct 15, 2026Задача: 1273. Delete Tree Nodes Сложность: medium Дерево, укорененное в узле 0, задано сле…
  4. Oct 14, 2026Задача: 724. Find Pivot Index Сложность: easy Если задан массив целых чисел nums, вычислит…
  5. Oct 14, 2026Задача: 674. Longest Continuous Increasing Subsequence Сложность: easy Дан неотсортированн…
  6. Oct 13, 2026Задача: 899. Orderly Queue Сложность: hard Вам дана строка s и целое число k. Вы можете вы…
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 →