Merge Trees
BINARY TREE
Problem
Given two binary trees root1
and root2
, merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum their values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.
Examples
mergeTrees([1,3,2,5], [2,1,3,null,4,null,7]) // returns [3,4,5,5,4,null,7] /*Nodes that overlap have their values summed. For example, the root nodes 1 and 2 merge to 3. Where one tree has a node and the other doesn't the non-null value is used. */ mergeTrees([1], [1,2]) // returns [2,2] // Only the primary branches overlap, resulting in a combined value.
Loading...
1
3
5
0
2
2
1
0
4
3
0
7