# Leetcode Python超琐碎笔记: 617. Merge Two Binary Trees

### 问题描述

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.

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.

Example 1:

``````Input:
Tree 1                     Tree 2
1                         2
/ \                       / \
3   2                     1   3
/                           \   \
5                             4   7

Output:
Merged tree:
3
/ \
4   5
/ \   \
5   4   7
``````

Note: The merging process must start from the root nodes of both trees.

### 我的实现及调优过程

##### 方法1：100 ms

``````# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
return merge(t1, t2)

def merge(t1, t2):
if t1 is None:
return t2
elif t2 is None:
return t1
else:
t1.val = t1.val + t2.val
t1.left = merge(t1.left, t2.left)
t1.right = merge(t1.right, t2.right)
return t1
``````
• 时间复杂度：O(n) （`n``merged tree`的节点数）
• 空间复杂度：O(1) （未创建新变量，但实际上递归本身的栈会占用一些资源）

### 推荐阅读更多精彩内容

• rljs by sennchi Timeline of History Part One The Cognitiv...
• 如果，你在乎我。 可不可以让我知道，不要总是让我找你，那会让我感觉，你根本就不在意我。 如果，你在乎我。 就不要总...
• 有一些东西是不需要刻意的。 比如我遇上这本书是在楼下的“粒多屋”甜品店里。只是很偶然地推门进去点了一份榴莲班戟，弯...
• 那是的我不是最好的我 那是的他已是最好的他 最好的我们 隔了整个青春 是不能跨越的青春 青春大概 走过了很多的故事...