leetcode617 Merge Two Binary Trees

 1 """
 2 Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
 3 You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.
 4 Example 1:
 5 Input:
 6     Tree 1                     Tree 2
 7           1                         2
 8          /                        / 
 9         3   2                     1   3
10        /                              
11       5                             4   7
12 Output:
13 Merged tree:
14          3
15         / 
16        4   5
17       /    
18      5   4   7
19 """
20 class TreeNode:
21     def __init__(self, x):
22         self.val = x
23         self.left = None
24         self.right = None
25 
26 class Solution:
27     def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
28         if t1 == None:
29             return t2
30         if t2 == None:
31             return t1
32         if t1 and t2 == None:
33             return None
34         result = TreeNode(t1.val + t2.val)
35         result.left = self.mergeTrees(t1.left, t2.left)
36         result.right = self.mergeTrees(t1.right, t2.right)
37         return result
38         # Solution2
39         # t1.val += t2.val
40         # t1.left = self.mergeTrees(t1.left, t2.left)
41         # t1.right = self.mergeTrees(t1.right, t2.right)
42         # return t1
43 """
44 此题尚未实现迭代法,但可以省去result空间
45 """
原文地址:https://www.cnblogs.com/yawenw/p/12253956.html