This approach leverages the in-order traversal property of Binary Search Trees (BSTs), which yields elements in sorted order. We perform an in-order traversal on both trees to extract elements into separate lists. We then merge these two sorted lists into one sorted list.
Time Complexity: O(n + m) where n and m are the number of nodes in root1 and root2, respectively. Space Complexity: O(n + m) for storing the elements from both trees.
1class TreeNode:
2 def __init__(self, x):
3 self.val = x
4 self.left = None
5 self.right = None
6
7class Solution:
8 def getAllElements(self, root1, root2):
9 def inOrder(node):
10 return inOrder(node.left) + [node.val] + inOrder(node.right) if node else []
11
12 list1, list2 = inOrder(root1), inOrder(root2)
13 return sorted(list1 + list2)
14
The Python solution uses an in-order traversal function that returns a list. By leveraging this function, we build sorted lists from both trees and concatenate them before returning the fully sorted list using Python's built-in sorted function.
This approach uses stacks to perform an iterative in-order traversal of both trees simultaneously. We make use of two separate stacks to store the nodes of current branches of the trees. The smallest node from the top of the stacks is chosen and processed to build the result list in sorted order.
Time Complexity: O(n + m) for processing all nodes, where n and m are the numbers of nodes in the two trees. Space Complexity: O(h1 + h2) where h1 and h2 are the heights of the two trees for the stack size.
1function TreeNode(val, left = null, right = null) {
2 this.val = (val===undefined ? 0 : val)
3 this.left = (left===undefined ? null : left)
4 this.right = (right===undefined ? null : right)
5}
6
7var getAllElements = function(root1, root2) {
8 let stack1 = [], stack2 = [], result = [];
9
10 while (root1 || root2 || stack1.length > 0 || stack2.length > 0) {
11 while (root1) {
12 stack1.push(root1);
13 root1 = root1.left;
14 }
15 while (root2) {
16 stack2.push(root2);
17 root2 = root2.left;
18 }
19
20 let val1 = (!stack1.length) ? Number.MAX_SAFE_INTEGER : stack1[stack1.length-1].val;
21 let val2 = (!stack2.length) ? Number.MAX_SAFE_INTEGER : stack2[stack2.length-1].val;
22
23 if (val1 <= val2) {
24 root1 = stack1.pop();
25 result.push(root1.val);
26 root1 = root1.right;
27 } else {
28 root2 = stack2.pop();
29 result.push(root2.val);
30 root2 = root2.right;
31 }
32 }
33
34 return result;
35};
36
The JavaScript solution adapts iterative two-stack traversal, coalescing both binary tree node sequences by handling dual stack comparisons. The out-of-call-stack approach facilitates an overlap-resistant node processing order that builds a final sorted array with consistent attention to element precedence.