1 minute read

Given two binary trees node0 and node1, return a merge of the two trees where each value is equal to the sum of the values of the corresponding nodes of the input trees. If only one input tree has a node in a given position, the corresponding node in the new tree should match that input node.

Constraints

  • n ≤ 100,000 where n is the number of nodes in node0
  • m ≤ 100,000 where m is the number of nodes in node1

https://binarysearch.com/problems/Merging-Binary-Trees

ExamplesPermalink

Example 1Permalink

Input

  • node0 =
example1Node0 0 0 1 3 0->1 2 2 0->2 3 3 2->3
  • node1 =
example1Node1 0 7 1 5 0->1 2 1 0->2

Output

  • answer =
example1Output 0 7 1 8 0->1 2 3 0->2 3 3 2->3

Example 2Permalink

Input

  • node0 =
example2Node0 0 1 1 2 0->1 2 3 1->2
  • node1 =
example2Node1 0 4 1 5 0->1 2 6 1->2

Output

  • answer =
example2Output 0 5 1 2 0->1 2 5 0->2 3 3 1->3 4 6 2->4

SolutionPermalink

/**
* class Tree {
* public:
* int val;
* Tree *left;
* Tree *right;
* };
*/
Tree *solve(Tree *node0, Tree *node1)
{
if (!node0 || !node1)
{
// no need to merge
return node0 ? node0 : node1;
}
else
{
// merge
node0->val += node1->val;
node0->left = solve(node0->left, node1->left);
node0->right = solve(node0->right, node1->right);
return node0;
}
}

Leave a comment