Leetcode 1305: All Elements in Two Binary Search Trees

grid47
grid47
Exploring patterns and algorithms
Jun 29, 2024 7 min read

Given two binary search trees, root1 and root2, return a list containing all the integers from both trees, sorted in ascending order.
Problem
Approach
Steps
Complexity
Input: Each tree is represented by its root node, and the nodes of the tree follow the binary search tree property where left child < parent node < right child.
Example: Input: root1 = [3, 1, 4], root2 = [2, 0, 5]
Constraints:
• The number of nodes in each tree is in the range [0, 5000].
• -105 <= Node.val <= 105
Output: Return a sorted list containing all the integers from both trees.
Example: Output: [0, 1, 2, 3, 4, 5]
Constraints:
• The output list will contain the sorted integers from both input trees.
Goal: To merge the two binary search trees and return the merged list of elements sorted in ascending order.
Steps:
• Use a two-pointer or stack-based approach to traverse both trees in in-order (left, root, right) fashion.
• Merge the results of both traversals and return the combined sorted list.
Goal: The solution must handle trees with up to 5000 nodes efficiently.
Steps:
• The number of nodes in each tree is between 0 and 5000.
• Node values are between -105 and 105.
Assumptions:
• Both trees are valid binary search trees.
• The solution should be efficient enough to handle trees with up to 5000 nodes.
Input: Input: root1 = [3, 1, 4], root2 = [2, 0, 5]
Explanation: The combined elements from both trees are [3, 1, 4] and [2, 0, 5]. Sorting these values gives [0, 1, 2, 3, 4, 5].

Input: Input: root1 = [6, null, 10], root2 = [5, 2, 7]
Explanation: The combined elements from both trees are [6, 10] and [5, 2, 7]. Sorting these values gives [2, 5, 6, 7, 10].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus