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 <stdio.h>
2#include <stdlib.h>
3
4struct TreeNode {
5 int val;
6 struct TreeNode *left;
7 struct TreeNode *right;
8};
9
10struct TreeNode* mergeTrees(struct TreeNode* root1, struct TreeNode* root2) {
11 if (!root1) return root2;
12 if (!root2) return root1;
13 root1->val += root2->val;
14 root1->left = mergeTrees(root1->left, root2->left);
15 root1->right = mergeTrees(root1->right, root2->right);
16 return root1;
17}
This C solution uses a recursive function mergeTrees
. We check if either of the current nodes is null and return the other node. If neither is null, we sum their values, then recursively merge their left and right 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.
1import
This Java solution also uses an iterative approach with a Stack, processing nodes iteratively for merging and pushing children onto the stack for later processing, similar to the depth-first strategy.