617. 合并二叉树
给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。
你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。
示例 1:
输入:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
输出:
合并后的树:
3
/ \
4 5
/ \ \
5 4 7
**注意: **合并必须从两个树的根节点开始。
思路:
用递归的方法解决,所谓合并二叉树,是将对应的节点合并
- 当前节点t1和t2均为空时,返回None
- 当前节点t1和t2不全为空时,分情况得到合并后根节点的值,对左右子树进行合并,最后返回根节点
class Solution:
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
t1_left, t1_right, t2_left, t2_right = None, None, None, None
if not t1 and not t2:
return None
elif t1 and not t2:
root = TreeNode(t1.val)
t1_left, t1_right = t1.left, t1.right
elif not t1 and t2:
root = TreeNode(t2.val)
t2_left, t2_right = t2.left, t2.right
else:
root = TreeNode(t1.val + t2.val)
t1_left, t1_right = t1.left, t1.right
t2_left, t2_right = t2.left, t2.right
root.left = self.mergeTrees(t1_left, t2_left)
root.right = self.mergeTrees(t1_right, t2_right)
return root