All Elements in Two Binary Search Trees (LeetCode 1305): Solution and Explanation

Medium
Tree
Depth First Search
Binary Search Tree
Sorting
Binary Tree

Given two binary search trees, return every value from both of them in one ascending list, keeping duplicates.

Intuition

A binary search tree read in inorder (left, node, right) comes out sorted. So each tree is really a sorted list in disguise, and the task is the merge step of merge sort.

You could write both inorder lists out and merge them. The neater version merges while walking: an iterative inorder traversal keeps a stack whose top is always the smallest value of that tree not yet output.

With one such stack per tree, each step compares the two tops, outputs the smaller one, and advances only that tree's traversal. That is exactly a two-pointer merge, with the stacks playing the role of the pointers.

Approach: Two inorder stacks, merged on the fly

  1. Keep a stack and a current pointer for each tree, starting at the roots.
  2. Push the current node and keep going left until null, for each tree. Now each stack top is that tree's smallest remaining value.
  3. If stack 2 is empty, or stack 1 is not empty and its top is less than or equal to stack 2's top, pop from stack 1; otherwise pop from stack 2.
  4. Append the popped value and set that tree's pointer to the popped node's right child.
  5. Repeat until both pointers are null and both stacks are empty.

Step-by-step example

root1 = [2,1,4], root2 = [1,0,3]
  1. Push the left spines: stack 1 holds 2, 1 (top 1) and stack 2 holds 1, 0 (top 0).
  2. 1 > 0, so output 0 from tree 2. Its right subtree is empty.
  3. Tops are 1 and 1. The tie goes to tree 1: output 1. Then 2 > 1, so output tree 2's 1, whose right child 3 is pushed.
  4. Tops are 2 and 3: output 2, then push 4 from tree 1's right subtree.
  5. Tops are 4 and 3: output 3, then stack 2 is empty, so output 4. The result is [0,1,1,2,3,4].

Code: Python, Java, C++

1class Solution:
2    def getAllElements(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> List[int]:
3        s1, s2, out = [], [], []
4        while root1 or root2 or s1 or s2:
5            while root1:
6                s1.append(root1)
7                root1 = root1.left
8            while root2:
9                s2.append(root2)
10                root2 = root2.left
11            if not s2 or (s1 and s1[-1].val <= s2[-1].val):
12                root1 = s1.pop()
13                out.append(root1.val)
14                root1 = root1.right
15            else:
16                root2 = s2.pop()
17                out.append(root2.val)
18                root2 = root2.right
19        return out
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m + n)

Every node of both trees is pushed once and popped once, and each pop does one comparison.

Space

O(h1 + h2)

Each stack holds at most one root-to-leaf path of its tree, not counting the output list itself.

Other approaches

Two inorder lists, then merge (time O(m + n), space O(m + n))

Run a recursive inorder traversal on each tree into a list, then merge the two sorted lists with two pointers. Simple and the same time, but it stores both lists in full.

Collect and sort (time O((m + n) log(m + n)), space O(m + n))

Gather all values in any order and sort them. Easiest to write, but it ignores the BST order and pays for a full sort.

Common mistakes

  • Forgetting to drain the second tree after the first runs out. The loop must continue while either stack or either pointer is non-empty.
  • Peeking at an empty stack. Check emptiness before comparing the tops.
  • Pushing only the popped node's right child instead of the whole left spine of the right subtree. The next smallest value is the leftmost node of that subtree.

Frequently asked questions

Why does the top of the stack always hold the smallest remaining value?

After pushing a left spine, the top is the leftmost unvisited node. Every value still waiting in that tree is either above it on the stack or in right subtrees of stacked nodes, and all of those are larger in a BST.

How are duplicates handled?

Equal values from both trees are both output. The tie rule (take from tree 1 on equal tops) just fixes the order, which does not change the sorted list.

Is the stack-based merge faster than building two lists?

Both are linear time. The stack version only saves memory: it keeps two root-to-leaf paths instead of two full lists.