> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/search/tree-traversal.md).

# 二叉树的遍历与搜索

### 四种遍历

* **先序**（根左右）：用于复制树
* **中序**（左根右）：BST 中序得到有序序列
* **后序**（左右根）：用于释放内存
* **层序**（逐层）：借助队列

```cpp
struct Node { int val; Node *left, *right; };

void preorder(Node* r) { if (!r) return; cout << r->val << " "; preorder(r->left); preorder(r->right); }
void inorder(Node* r)  { if (!r) return; inorder(r->left); cout << r->val << " "; inorder(r->right); }
void postorder(Node* r){ if (!r) return; postorder(r->left); postorder(r->right); cout << r->val << " "; }

void levelOrder(Node* root) {
    if (!root) return;
    queue<Node*> q; q.push(root);
    while (!q.empty()) {
        Node* cur = q.front(); q.pop();
        cout << cur->val << " ";
        if (cur->left)  q.push(cur->left);
        if (cur->right) q.push(cur->right);
    }
}
```

### 由遍历序列还原二叉树

* 已知**先序 + 中序**，可唯一确定一棵二叉树；
* 已知**后序 + 中序**，也可唯一确定；
* 仅知先序 + 后序一般**不能**唯一确定。

### 二叉树的搜索

在 BST 中查找某值，根据大小关系决定往左还是往右，平均 O(log n)，即“二叉树的搜索算法”。


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/search/tree-traversal.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
