TGViewer
Java | LeetCode Java | LeetCode @easy_java_task · 6.44K subscribers
Post #1846 688
Задача: 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 {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}

class Solution {
public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
ArrayDeque<TreeNode> stack1 = new ArrayDeque<>(), stack2 = new ArrayDeque<>();
List<Integer> output = new ArrayList<>();

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.peek().val <= stack2.peek().val)) {
root1 = stack1.pop();
output.add(root1.val);
root1 = root1.right;
} else {
root2 = stack2.pop();
output.add(root2.val);
root2 = root2.right;
}
}
return output;
}
}


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_java_task
  1. Oct 13, 2026Post #2296
  2. Oct 13, 2026Задача: 1120. Maximum Average Subtree Сложность: medium Дан корень бинарного дерева. Верни…
  3. Oct 13, 2026Post #2294
  4. Oct 12, 2026Задача: 1413. Minimum Value to Get Positive Step by Step Sum Сложность: easy Дан массив це…
  5. Oct 11, 2026Задача: 672. Bulb Switcher II Сложность: medium Есть комната с n лампочками, пронумерованн…
  6. Oct 10, 2026Задача: 723. Candy Crush Сложность: medium Этот вопрос касается реализации базового алгори…
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 →