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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/115017.html
標籤:Python
上一篇:JAVA執行緒池
