Merge BSTs to Create Single BST — LeetCode 1932 Python Solution

HardTreeDepth-First SearchHash TableBinary SearchBinary Tree
Problem
#1932
Reading time
2 min

The problem

You are given n BST (binary search tree) root nodes for n separate BSTs stored in an array trees (0-indexed). Each BST in trees has at most 3 nodes, and no two roots have the same value.

Example

Input
trees = [[2,1],[3,2,5],[5,4]]
Output
[3,2,5,1,null,4]
Explanation
In the first operation, pick i=1 and j=0, and merge trees[0] into trees[1].

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1932. Merge BSTs to Create Single BST is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1932. Merge BSTs to Create Single BST?
LeetCode 1932. Merge BSTs to Create Single BST is rated Hard on LeetCode.
What is the time complexity of LeetCode 1932. Merge BSTs to Create Single BST?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1932. Merge BSTs to Create Single BST?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1932. Merge BSTs to Create Single BST cover?
LeetCode 1932. Merge BSTs to Create Single BST is tagged Tree, Depth-First Search, Hash Table, Binary Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview