# LeetCode #617 合并二叉树 树 递归

## LeetCode #617 合并二叉树

### 题目描述

输入:
Tree 1                     Tree 2
1                         2
/ \                       / \
3   2                     1   3
/                           \   \
5                             4   7

3
/ \
4   5
/ \   \
5   4   7


#### 方法一：递归

# 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: TreeNode, t2: TreeNode) -> TreeNode:
if not t1 and t2:
return t2
elif t1 and t2:
t1.val = t1.val + t2.val
t1.left = self.mergeTrees(t1.left, t2.left)
t1.right = self.mergeTrees(t1.right, t2.right)
# t1 and not t2
# else:
#     return t1
return t1

• 时间复杂度：$O(N)$
• 空间复杂度：$O(N)$

#### 方法二：递归

# 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: TreeNode, t2: TreeNode) -> TreeNode:
if not t1 and t2:
return t2
elif t1 and t2:
stack = [(t1, t2)]
while stack:
r1, r2 = stack.pop(0)
r1.val += r2.val
# 如果r1和r2的左子树都存在就把r2的左子树挂在r1上
if r1.left and r2.left:
stack.append((r1.left, r2.left))
elif not r1.left:
r1.left = r2.left
# 右子树也是一样的
if r1.right and r2.right:
stack.append((r1.right, r2.right))
elif not r1.right:
r1.right = r2.right
# t1 and not t2
# else:
#     return t1
return t1

• 时间复杂度：$O(N)$
• 空间复杂度：$O(N)$

©️2019 CSDN 皮肤主题: 精致技术 设计师: CSDN官方博客