var mergeTrees = function(t1, t2) {
if (!t1 && !t2) return null;
const root = new TreeNode(((t1  0).val  0) + ((t2  0).val  0));
root.left = mergeTrees(t1 && t1.left, t2 && t2.left);
root.right = mergeTrees(t1 && t1.right, t2 && t2.right);
return root;
};
A few lines of JavaScript


@ChienWeiLuo I'd be happy to explain.
Since we return
null
when botht1
andt2
arenull
(do not exist), we have to account for the fact that one of them may benull
.(t1  0).val
gets the value of thet1
node whent1
exists, otherwise it getsundefined
since(0).val
isundefined
. Then because that is falsy,((t1  0).val  0)
is0
whent1
doesn't exist. We are using the fact thatfalsyValue  someValue
evaluates tosomeValue
, and this allows us to create that short line that would otherwise be a longer ternary or multiline conditional.We use a similar technique for
t1 && t1.left
sincefalsyValue && someValue
evaluates tofalsyValue
, and thereforenull
gets passed to the next recursion ift1
doesn't exist.The algorithm itself is a standard preorder DFS. Hope this helps.





@loctn
What's the different between (t1  0) and ((t1  0).val  0)?null  0 =>0
undefined  0 => 0I run these two in console and they have the same result.
Thanks.

@giltwg we need to add the values when they exist. When they don't exist they are
null
which doesn't have properties sincenull
is not an object but its own type (not obvious becausetypeof null
gives'object'
), so we have to "or" it to0
because(0).val
isundefined
which is falsy and will contribute zero to the sum.

@loctn My point is : Null is also a falsy value. So (null  0) will also contribute zero to the sum. Why should we use undefined? Thanks.

@giltwg because the times when the node is not falsy, there is a value there accessed by
.val
. We useundefined
simply because that is the value of a nonexistent property, in this case theval
property of0
, but we don't prefer it for any other particular reason. Basically, it doesn't matter what the second term is in(t1  0)
 we could have used(t1  {})
 but I chose0
for brevity.



Hi!
Nevermind, I forgot the null when returning, it was expected for the printer
I came up with a solution that's basically the same as you two:var mergeTrees = function(t1, t2) { if (!t1 && !t2) return null if (!t1  !t2) return t1  t2 const newNode = new TreeNode(t1.val + t2.val) newNode.left = mergeTrees(t1.left, t2.left) newNode.right = mergeTrees(t1.right, t2.right) return newNode };