> For the complete documentation index, see [llms.txt](https://jenhsuan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jenhsuan.gitbook.io/algorithm/leetcode/105.-construct-binary-tree-from-preorder-and-inorder-traversal.md).

# 105. Construct Binary Tree from Preorder and Inorder Traversal

## 1.問題&#x20;

![](/files/-LOSZUzhfTMAVimGMjbN)

## 2.想法 <a href="#id-2-xiang-fa" id="id-2-xiang-fa"></a>

* 提問
  * 確認題意:  root是NULL是true或false?
* function header, parameter
* r input
* 說明想法
  * 由preorder可以決定root node是誰, 接著藉著left, right尋找落在inorder的位置, 找出作為下一層的搜尋索引
* 測試計算複雜度

## **3.程式碼** <a href="#id-3-cheng-shi" id="id-3-cheng-shi"></a>

```
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        if (preorder.size() == 0) {
            return NULL;
        }
        int pos = 0;
        return buildNewTree(preorder, inorder, 0, preorder.size() - 1, pos);
    }
private:
    TreeNode* buildNewTree(vector<int>& preorder, vector<int>& inorder, int left, int right, int& pos) {
        if (pos >= preorder.size() || left > right) {
            return NULL;
        }
        
        int i = 0;
        for (i = left; i <= right; i++) {
            if (preorder[pos] == inorder[i]) {
                break;
            }
        }
        
        TreeNode* node = new TreeNode(preorder[pos]);
        pos++;
        node->left = buildNewTree(preorder, inorder, left, i - 1, pos);
        node->right = buildNewTree(preorder, inorder, i + 1, right, pos);
        
        return node;
    }
};
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://jenhsuan.gitbook.io/algorithm/leetcode/105.-construct-binary-tree-from-preorder-and-inorder-traversal.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.
