Sponsored
Sponsored
This approach utilizes recursion to traverse both trees simultaneously. If both node values are non-null, we sum them up as the new value and recursively merge their left and right children. If one node is null, we return the non-null node.
Time Complexity: O(n); Space Complexity: O(h), where n is the total number of nodes and h is the height of the tree.
1#include <iostream>
2using namespace std;
3
4struct TreeNode {
5 int val;
6 TreeNode* left;
7 TreeNode* right;
8 TreeNode(int x) : val(x), left(NULL), right(NULL) {}
9};
10
11TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
12 if (!root1) return root2;
13 if (!root2) return root1;
14 root1->val += root2->val;
15 root1->left = mergeTrees(root1->left, root2->left);
16 root1->right = mergeTrees(root1->right, root2->right);
17 return root1;
18}
This C++ solution uses a similar recursive function. If either node is null, it returns the other. Otherwise, it sums their values and recursively processes their children.
This approach uses an iterative method with a stack to simulate the recursive calls for merging the two binary trees. We traverse the trees using a stack and merge nodes at each level iteratively.
Time Complexity: O(n); Space Complexity: O(h), where n is the total number of nodes and h is the maximum height of the two trees.
1function
In this JavaScript solution, an iterative approach utilizing a stack is employed. Nodes are iteratively processed and summed, with their children managed in a stack for future processing.