LeetCode--617--合併二叉樹(python)

給定兩個二叉樹,想象當你將它們中的一個覆蓋到另外一個上時,兩個二叉樹的一些節點便會重疊。spa

你須要將他們合併爲一個新的二叉樹。合併的規則是若是兩個節點重疊,那麼將他們的值相加做爲節點合併後的新值,不然不爲 NULL 的節點將直接做爲新二叉樹的節點。code

示例 1:blog

輸入:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
輸出:
合併後的樹:
3
/ \
4 5
/ \ \
5 4 7
注意: 合併必須從兩個樹的根節點開始。io

 

1 class Solution:
2     def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
3         if not t1 and t2:
4             return t2
5         elif t1 and t2:
6             t1.val = t1.val + t2.val
7             t1.left = self.mergeTrees(t1.left,t2.left)
8             t1.right = self.mergeTrees(t1.right,t2.right)
9         return t1
相關文章
相關標籤/搜索