This needs to be done at every recurrence as we traverse through the trees. However, the traversal needs to be done before we return tree1-- the intuition being that we need to adjust the children of each node before we can give it back. In other words, we should write the merge results on the first tree before presenting it back in our method.
xxxxxxxxxx
14
function mergeTwoBinaryTrees(tree1, tree2) {
if (tree1 == null) {
return tree2;
}
if (tree2 == null) {
return tree1;
}
tree1.val += tree2.val
​
tree1.left = mergeTwoBinaryTrees(tree1.left, tree2.left);
tree1.right = mergeTwoBinaryTrees(tree1.right, tree2.right);
​
return tree1;
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment