617合并二叉树

class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# 这道也是简单题,也是用深搜的办法来做的。
# 遍历每一个节点,然后如果这个节点两个树都有的话就加到第一个树上边。
# 如果第二个树有而第一个树没有的话,就将第一个树的节点指向个树。
class Solution:
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
# 判断两个树是否为空
if not t1 and t2:
return t2
elif not t2 and t1:
return t1
elif not t1 and not t2:
return t1
else:
# 注意这里如果两个树都不为空的时候,注意是否只有根节点。
t1.val += t2.val
if not t1.left and not t1.right and not t2.left and not t2.right:
return t1
else:
self.dfs(t1,t2)
return t1
def dfs(self,root1,root2):
# 两个树的节点的左儿子都不为空,就加到第一个树的节点上边。
if root1.left and root2.left :
root1.left.val += root2.left.val
# 然后继续进行遍历
self.dfs(root1.left,root2.left)
# 如果两个树的左儿子节点都为空,或者第一个树的左儿子节点不为空,
# 不用进行改变。
# 如果第二个树的左儿子节点不为空,第一个树的左儿子节点为空,
# 那么就将第一个树的指针指向第二个树的左儿子节点。
elif not root1.left and root2.left:
root1.left = root2.left
# 右子树和左子树一样的。

if root1.right and root2.right :
root1.right.val += root2.right.val
self.dfs(root1.right,root2.right)
elif not root1.right and root2.right:
root1.right = root2.right

posted @ 2020-09-23 19:58  月为暮  阅读(445)  评论(0编辑  收藏  举报