# 07.重建二叉树

### 一、 题目

输入某二叉树的前序遍历和中序遍历的结果，请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

例如，给出

前序遍历 preorder = \[3,9,20,15,7]

中序遍历 inorder = \[9,3,15,20,7]

返回如下的二叉树：

```
3
/ \
9  20
    /  \
    15   7
```

限制：

0 <= 节点个数 <= 5000

链接：<https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof>

著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。

### 二、 解法

```
func buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? {
    guard preorder.isEmpty == false, inorder.isEmpty == false else {
        return nil
    }
    
    let root = TreeNode(preorder[0], nil, nil)
    
    /**
     对中序的进行遍历，寻找根结点在其中的位置
     从而划分左右中序遍历结果
     */
    for (idx, node) in inorder.enumerated() {
        if node == preorder[0] { // 找到根结点
            root.left = buildTree(
                Array(preorder[1..<idx+1]),// 根结点在中序中的下标可以算出其 左子树的元素数量
                Array(inorder[0..<idx]))
            root.right = buildTree(
                Array(preorder[idx+1..<preorder.endIndex]),// 根结点在中序中的下标可以算出其 右子树的元素数量
                Array(inorder[idx+1..<inorder.endIndex]))
        }
    }
    
    return root
}
```


---

# 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://ryukiedev.gitbook.io/wiki/shu-ju-jie-gou-yu-suan-fa/jian-zhi-offerswift/07.-zhong-jian-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.
