
Sponsored
Sponsored
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.
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 const inOrder = (node) => node ? [...inOrder(node.left), node.val, ...inOrder(node.right)] : [];
9 const list1 = inOrder(root1);
10 const list2 = inOrder(root2);
11
12 let merged = [], i = 0, j = 0;
13 while (i < list1.length && j < list2.length) {
14 if (list1[i] < list2[j])
15 merged.push(list1[i++]);
16 else
17 merged.push(list2[j++]);
18 }
19 return merged.concat(list1.slice(i)).concat(list2.slice(j));
20};
21This JavaScript solution applies in-order traversal to produce sorted arrays from both binary trees. Next, these arrays are merged utilizing two-pointer technique, resulting in a single sorted array which is returned.
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.
This Java implementation utilizes two stacks to iteratively perform an in-order traversal, which avoids recursion limitations and processes each node whenever its tree reaches a leaf. By popping from the stack with the smaller node, it guarantees ordered addition, efficiently managing space through finely scoped stack depth utilization.