給定兩個二叉樹,想象當你將它們中的一個覆蓋到另一個上時,兩個二叉樹的一些節點便會重疊。
你需要將他們合併爲一個新的二叉樹。合併的規則是如果兩個節點重疊,那麼將他們的值相加作爲節點合併後的新值,否則不爲 NULL 的節點將直接作爲新二叉樹的節點。
輸入:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
輸出:
合併後的樹:
3
/ \
4 5
/ \ \
5 4 7
有很多解法能處理這個問題:主要有遞歸,迭代,DFS,BFS
首先想到的就是利用樹的前序,中序,後序遍歷處理
遞歸
前序遍歷解法
class Solution(object):
def mergeTrees(self, t1, t2):
if t1 is None and t2 is None:
return
if t1 is None:
return t2
if t2 is None:
return t1
t = TreeNode(t1.val + t2.val)
t.left = self.mergeTrees(t1.left, t2.left)
t.right = self.mergeTrees(t1.right, t2.right)
return t
中序遍歷解法
class Solution(object):
def mergeTrees(self, t1, t2):
if t1 is None and t2 is None:
return
if t1 is None:
return t2
if t2 is None:
return t1
t_left = self.mergeTrees(t1.left, t2.left)
t = TreeNode(t1.val + t2.val)
t.left = t_left
t.right = self.mergeTrees(t1.right, t2.right)
return t
後序遍歷解法
class Solution(object):
def mergeTrees(self, t1, t2):
if t1 is None and t2 is None:
return
if t1 is None:
return t2
if t2 is None:
return t1
t_left = self.mergeTrees(t1.left, t2.left)
t_right = self.mergeTrees(t1.right, t2.right)
t = TreeNode(t1.val + t2.val)
t.left = t_left
t_right = t_right
return t
迭代,BFS
class Solution(object):
def mergeTrees(self, t1, t2):
"""
迭代合併
:param t1:
:param t2:
:return:
"""
if t1 is None and t2 is None:
return None
if t1 is None:
return t2
if t2 is None:
return t1
t = TreeNode(t1.val + t2.val)
q1 = [t1] # 存第一個要合併的節點
q2 = [t2] # 存第二個要合併的節點
q = [t] # 存新節點
while len(q) > 0:
node = q.pop(0)
t1 = q1.pop(0)
t2 = q2.pop(0)
if t1.left is None and t2.left is None:
pass
elif t1.left is None:
node.left = t2.left
elif t2.left is None:
node.left = t1.left
else:
node.left = TreeNode(t1.left.val + t2.left.val)
q.append(node.left)
q1.append(t1.left)
q2.append(t2.left)
if t1.right is None and t2.right is None:
pass
elif t1.right is None:
node.right = t2.right
elif t2.right is None:
node.right = t1.right
else:
node.right = TreeNode(t1.right.val + t2.right.val)
q.append(node.right)
q1.append(t1.right)
q2.append(t2.right)
return t