题目:力扣
思路:树的合并看成节点的合并,注意节点为null的处理
代码:
var mergeTrees = function(root1, root2) {
if (!root1 && !root2) return null
return {
val: (root1 ? root1.val : 0) + (root2 ? root2.val : 0),
left: mergeTrees(root1 ? root1.left : null, root2 ? root2.left : null),
right: mergeTrees(root1 ? root1.right : null, root2 ? root2.right : null)
}
};
结果: