Leetcode 617. 合并二叉树
617. 合并二叉树 - 力扣(LeetCode) (leetcode-cn.com)

思路 深度优先搜索——>递归
1. 从根节点开始,遍历每一个子节点
2. 如果其中一个树的节点为空,将该节点置位另一个树的节点。
3. 如果两个树的节点都不为空,则将val相加。
4. 对当前节点的左右节点都进行merge。
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func mergeTrees(root1 *TreeNode, root2 *TreeNode) *TreeNode {
if root1 == nil {
return root2
}
if root2 == nil {
return root1
}
root1.Val += root2.Val
root1.Left = mergeTrees(root1.Left, root2.Left)
root1.Right = mergeTrees(root1.Right, root2.Right)
return root1
}

浙公网安备 33010602011771号