All Elements in Two Binary Search Trees
Medium · Tree, Depth-First Search, Binary Search Tree, Sorting, Binary Tree
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
Starter code (python)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def getAllElements(self, root1, root2):
"""
:type root1: Optional[TreeNode]
:type root2: Optional[TreeNode]
:rtype: List[int]
"""
Related problems
- 3Sum (Medium)
- 3Sum Closest (Medium)
- 4Sum (Medium)
Previous: Find N Unique Integers Sum up to Zero · Next: Minimum Insertion Steps to Make a String Palindrome · All problems
Zepruv is a technical interview practice platform. Read any problem for free; sign in to run your code, submit and keep your progress.