TGViewer
PHP | LeetCode PHP | LeetCode @easy_php_task · 1.33K subscribers
Post #787 178
Задача: 1305. All Elements in Two Binary Search Trees
Сложность: medium

Даны два бинарных дерева поиска root1 и root2. Вернуть список, содержащий все целые числа из обоих деревьев, отсортированные в порядке возрастания.

Пример:
Input: root1 = [2,1,4], root2 = [1,0,3]
Output: [0,1,1,2,3,4]


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

1⃣Выполните итеративный обход в порядке возрастания обоих деревьев параллельно.

2⃣На каждом шаге добавляйте наименьшее доступное значение в выходной список.

3⃣Верните выходной список.

😎 Решение:
class TreeNode {
public $val;
public $left;
public $right;
function __construct($val = 0, $left = null, $right = null) {
$this->val = $val;
$this->left = $left;
$this->right = $right;
}
}

class Solution {
function getAllElements($root1, $root2) {
$stack1 = new SplStack();
$stack2 = new SplStack();
$output = [];

while ($root1 !== null || $root2 !== null || !$stack1->isEmpty() || !$stack2->isEmpty()) {
while ($root1 !== null) {
$stack1->push($root1);
$root1 = $root1->left;
}
while ($root2 !== null) {
$stack2->push($root2);
$root2 = $root2->left;
}
if ($stack2->isEmpty() || (!$stack1->isEmpty() && $stack1->top()->val <= $stack2->top()->val)) {
$root1 = $stack1->pop();
$output[] = $root1->val;
$root1 = $root1->right;
} else {
$root2 = $stack2->pop();
$output[] = $root2->val;
$root2 = $root2->right;
}
}
return $output;
}
}


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