Merge BSTs to Create Single BST — LeetCode 1932 Python Solution
- Problem
- #1932
- Pattern
- Tree Traversal
- Reading time
- 2 min
- Source
- leetcode.com
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.