LeetCode 1305. All Elements in Two Binary Search Trees Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1305. All Elements in Two Binary Search Trees

Description

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

Solutions

Solution 1: DFS + Merge

Since both trees are binary search trees, we can obtain the node value sequences a and b of the two trees through in-order traversal. Then, we use two pointers to merge the two sorted arrays to get the final answer.

The time complexity is O(n+m), and the space complexity is O(n+m). Here, n and m are the number of nodes in the two trees, respectively.

PythonJavaC++GoTypeScriptRust
# 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(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !