All Elements in Two Binary Search Trees — LeetCode 1305 Python Solution

MediumTreeDepth-First SearchBinary Search TreeBinary TreeSorting
Problem
#1305
Reading time
6 min

The problem

Given two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order.

Example

Input
root1 = [2,1,4], root2 = [1,0,3]
Output
[0,1,1,2,3,4]

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def getAllElements(
        self, root1: Optional[TreeNode], root2: Optional[TreeNode]
    ) -> List[int]:
        def dfs(root: Optional[TreeNode], nums: List[int]) -> int:
            if root is None:
                return
            dfs(root.left, nums)
            nums.append(root.val)
            dfs(root.right, nums)

        a, b = [], []
        dfs(root1, a)
        dfs(root2, b)
        m, n = len(a), len(b)
        i = j = 0
        ans = []
        while i < m and j < n:
            if a[i] <= b[j]:
                ans.append(a[i])
                i += 1
            else:
                ans.append(b[j])
                j += 1
        while i < m:
            ans.append(a[i])
            i += 1
        while j < n:
            ans.append(b[j])
            j += 1
        return ans

Complexity

MeasureComplexity
TimeO(n+m)
SpaceO(n+m) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1305. All Elements in Two Binary Search Trees is filed here because LeetCode tags it Tree, Binary Tree and Binary Search 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 1305. All Elements in Two Binary Search Trees?
LeetCode 1305. All Elements in Two Binary Search Trees is rated Medium on LeetCode.
What is the time complexity of LeetCode 1305. All Elements in Two Binary Search Trees?
The Python solution on this page runs in O(n+m).
What is the space complexity of LeetCode 1305. All Elements in Two Binary Search Trees?
The Python solution on this page uses O(n+m) auxiliary space.
What topics does LeetCode 1305. All Elements in Two Binary Search Trees cover?
LeetCode 1305. All Elements in Two Binary Search Trees is tagged Tree, Depth-First Search, Binary Search Tree, Binary Tree and Sorting 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