0.总结

  • 建议用时:10min

1.​​题目​​

就是将一棵二叉树对应合并起来。如果节点重叠了,则计算其和。

2.思想

  • 同时深搜两棵树,
  • 如果二者都有值,那么直接相加,如果只有一个有值,那么直接拼凑过来

3.代码

# 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: TreeNode, root2: TreeNode) -> TreeNode:
root = self.dfs(root1,root2)
return root

def dfs(self,r1,r2):
# 下面三个if则是用于判断当前节点是否是空节点,如果二者都是有效的,那么继续递归
# 如果只有一个是有效的,那么就返回非空的那个
if r1 is None and r2 is None: # 如果两个都没节点了
return None

if r1 is None and r2 is not None: # 1树为空,2树不为空
return r2

if r1 is not None and r2 is None:
return r1

# 递归处理左子树
left = self.dfs(r1.left,r2.left)

# 递归处理右子树
right = self.dfs(r1.right,r2.right)

# 获取值
val_1 = r1.val if r1 is not None else 0
val_2 = r2.val if r2 is not None else 0
r1.val = val_1 + val_2

# 更新节点
r1.left = left
r1.right = right
return r1 # 返回最后的根节点