617合并二叉树
给你两棵二叉树: root1 和 root2 。
想象一下,当你将其中一棵覆盖到另一棵之上时,两棵树上的一些节点将会重叠(而另一些不会)。你需要将这两棵树合并成一棵新二叉树。合并的规则是:如果两个节点重叠,那么将这两个节点的值相加作为合并后节点的新值;否则,不为 null 的节点将直接作为新二叉树的节点。
返回合并后的二叉树。
注意: 合并过程必须从两个树的根节点开始。
输入:root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]
输出:[3,4,5,5,4,null,7]
输入:root1 = [1], root2 = [1,2]
输出:[2,2]
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
# 非递归
# if not root1:return root2
# if not root2:return root1
# from collections import deque
# que = deque()
# que.append(root1)
# que.append(root2)
# while que:
# node1 = que.popleft()
# node2 = que.popleft()
# if node1.left and node2.left:
# que.append(node1.left)
# que.append(node2.left)
# if node1.right and node2.right:
# que.append(node1.right)
# que.append(node2.right)
# node1.val += node2.val
# if not node1.left and node2.left:
# node1.left = node2.left
# if not node1.right and node2.right:
# node1.right = node2.right
# return root1
# 递归
if not root1:return root2
if not root2:return root1
def helper(root1, root2):
root1.val += root2.val
if root1.left and root2.left:
helper(root1.left, root2.left)
if root1.right and root2.right:
helper(root1.right, root2.right)
if not root1.left and root2.left:
root1.left = root2.left
if not root1.right and root2.right:
root1.right = root2.right
helper(root1, root2)
return root1