Merge two BST

Pattern: BST iterator

medium

Run two inorder walks side by side, each with its own stack, and like the merge step of merge sort, always output the smaller of the two next values.

The problem

Return all values of two BSTs in one sorted list. The example gives [1, 2, 2, 3, 3, 4, 5, 6, 6, 7].

Think first

  • What order does each BST give you for free?
  • How do you merge two sorted streams?
  • Do you need to store both inorders first?

Hints

    Brute force, and why it fails

    Collect both inorders and sort the joined list: O((m + n) log(m + n)).

    The key insight

    Two paused inorder walks produce two sorted streams, which merge in linear time.

    Dry run

    out1

    BST a = [5, 3, 6, 2, 4], b = [2, 1, 3, null, null, null, 7, 6]. The next values are 2 (a) and 1 (b).

    Step 1 of 3

    The plan

    while either walk has values: push left chains; pop the smaller top; output it; continue from its right child
    

    Complexity

    Time
    O(m + n)
    Space
    O(h1 + h2)

    Every node is pushed and popped once.

    Edge cases

    • One tree empty.
    • Both empty.
    • Equal values in both.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<Integer> merge(TreeNode a, TreeNode b) {
            Deque<TreeNode> sa = new ArrayDeque<>(), sb = new ArrayDeque<>();   // two inorder walks side by side
            List<Integer> out = new ArrayList<>();
            while (a != null || b != null || !sa.isEmpty() || !sb.isEmpty()) {
                for (; a != null; a = a.left) sa.push(a);
                for (; b != null; b = b.left) sb.push(b);
                if (sb.isEmpty() || (!sa.isEmpty() && sa.peek().val <= sb.peek().val)) {   // take the smaller next value
                    TreeNode n = sa.pop();
                    out.add(n.val);
                    a = n.right;
                } else {
                    TreeNode n = sb.pop();
                    out.add(n.val);
                    b = n.right;
                }
            }
            return out;
        }
    }

    C++

    class Solution {
    public:
        vector<int> merge(TreeNode* a, TreeNode* b) {
            stack<TreeNode*> sa, sb;                // two inorder walks side by side
            vector<int> out;
            while (a != NULL || b != NULL || !sa.empty() || !sb.empty()) {
                for (; a != NULL; a = a->left) sa.push(a);
                for (; b != NULL; b = b->left) sb.push(b);
                if (sb.empty() || (!sa.empty() && sa.top()->val <= sb.top()->val)) {   // take the smaller next value
                    TreeNode* n = sa.top();
                    sa.pop();
                    out.push_back(n->val);
                    a = n->right;
                } else {
                    TreeNode* n = sb.top();
                    sb.pop();
                    out.push_back(n->val);
                    b = n->right;
                }
            }
            return out;
        }
    };

    Python

    class Solution:
        def merge(self, a, b) -> list[int]:
            sa, sb, out = [], [], []                # two inorder walks side by side
            while a or b or sa or sb:
                while a:
                    sa.append(a)
                    a = a.left
                while b:
                    sb.append(b)
                    b = b.left
                if not sb or (sa and sa[-1].val <= sb[-1].val):   # take the smaller next value
                    n = sa.pop()
                    out.append(n.val)
                    a = n.right
                else:
                    n = sb.pop()
                    out.append(n.val)
                    b = n.right
            return out

    Common mistakes

    • Inserting every value of one tree into the other.
    • Forgetting nodes left in one stack when the other is empty.

    Similar problems