题目:
给你两棵二叉树: root1 和 root2 。
想象一下,当你将其中一棵覆盖到另一棵之上时,两棵树上的一些节点将会重叠(而另一些不会)。你需要将这两棵树合并成一棵新二叉树。合并的规则是:如果两个节点重叠,那么将这两个节点的值相加作为合并后节点的新值;否则,不为 null 的节点将直接作为新二叉树的节点。
返回合并后的二叉树。
注意: 合并过程必须从两个树的根节点开始。
算法:
func mergeTrees(root1 *TreeNode, root2 *TreeNode) *TreeNode {
if root1 == nil && root2 == nil {
return nil
}
var r1Left, r2Left, r1Right, r2Right *TreeNode
node := &TreeNode{}
if root1 != nil {
node.Val = node.Val + root1.Val
r1Left = root1.Left
r1Right = root1.Right
}
if root2 != nil {
node.Val = node.Val + root2.Val
r2Left = root2.Left
r2Right = root2.Right
}
node.Left = mergeTrees(r1Left, r2Left)
node.Right = mergeTrees(r1Right, r2Right)
return node
}