1. Collect All Elements & Sort (O((N1+N2) log(N1+N2)))
Intuition
Visit all nodes in both trees and append their values into a single array. Sort the combined array using QuickSort or MergeSort. Takes O((N1 + N2) log(N1 + N2)) time and O(N1 + N2) space.
When to apply: Baseline comparison ignoring BST sorted properties.
Algorithm
- Traverse both trees using preorder/DFS, append all values to a list, and sort using a standard sorting algorithm.
#include <iostream>#include <vector>#include <algorithm> struct Node { int data; Node* left; Node* right; Node(int val) : data(val), left(nullptr), right(nullptr) {}}; class Solution { void collect(Node* root, std::vector<int>& vals) { if (!root) return; vals.push_back(root->data); collect(root->left, vals); collect(root->right, vals); }public: std::vector<int> merge(Node* root1, Node* root2) { std::vector<int> vals; collect(root1, vals); collect(root2, vals); std::sort(vals.begin(), vals.end()); return vals; }}; int main() { Node* root1 = new Node(3); root1->left = new Node(1); root1->right = new Node(5); Node* root2 = new Node(4); root2->left = new Node(2); root2->right = new Node(6); Solution sol; std::vector<int> res = sol.merge(root1, root2); for (int v : res) std::cout << v << " "; std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O((N1 + N2) log(N1 + N2)) - Space complexity:
O(N1 + N2)