# 617. 合并二叉树

<https://leetcode-cn.com/problems/merge-two-binary-trees/>

## 解法一：递归前序

思路:递归前序遍历二叉树算法的变种. 规则:&#x20;

(1)若t1 和 t2都非空,访问之.并创建新节点,val为t1和t2的val之和. 然后就是前序遍历那一套&#x20;

(2)若t1 t2其中有一个或两个为空,则直接返回另一个.(因为若t1已经为空,则merge之后的结果就只剩t2,直接拿过来就行.画图比较好理解)

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://cai-sen-se.gitbook.io/leetcode/601-800/617.-he-bing-er-cha-shu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
