Skip to main content

617. Merge Two Binary Trees

分析


题解

创建新的node


function mergeTrees(root1: TreeNode | null, root2: TreeNode | null): TreeNode | null {
const newRoot = new TreeNode()
if (root1 || root2) {
newRoot.val = (root1 ? root1.val : 0) + (root2 ? root2.val : 0)
} else {
return null
}
const newLeftNode = mergeTrees(root1?.left, root2?.left)
const newRightNode = mergeTrees(root1?.right, root2?.right)
newRoot.left = newLeftNode
newRoot.right = newRightNode
return newRoot
};

复用原有node

function mergeTrees(root1: TreeNode | null, root2: TreeNode | null): TreeNode | null {
if (!root1) {
return root2
}
if (!root2) {
return root1
}
root1.val = root1.val + root2.val
root1.left = mergeTrees(root1?.left, root2?.left)
root1.right = mergeTrees(root1?.right, root2?.right)
return root1
};