Talentd
FleetCode

1305. All Elements in Two Binary Search Trees

Medium80.5% acceptance2 companies

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

Example 1:

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

Example 2:

Input: root1 = [1,null,8], root2 = [8,1]
Output: [1,1,8,8]

Constraints:

  • The number of nodes in each tree is in the range [0, 5000].
  • -105 <= Node.val <= 105

Asked at 2 companies

Hints open one at a time

Hint 1
Traverse the first tree in list1 and the second tree in list2.
Hint 2
Merge the two trees in one list and sort it.
22:33
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1# Definition for a binary tree node.
2# class TreeNode:
3# def __init__(self, val=0, left=None, right=None):
4# self.val = val
5# self.left = left
6# self.right = right
7class Solution:
8 def getAllElements(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> List[int]:
9
Starter codePython 3Spaces: 4
Examples
Input
[2,1,4]
[1,0,3]
Input
[1,null,8]
[8,1]
Your code is saved on this device.Solution