> 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/data-structures/binary-search-tree.md).

# 二叉排序树

### 定义（BST）

二叉排序树（二叉查找树）满足：**左子树所有结点 < 根 < 右子树所有结点**，且左右子树也都是 BST。

### 作用

支持快速查找、插入、删除，平均时间复杂度 O(log n)。

### 查找

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

Node* find(Node* root, int x) {
    if (!root) return nullptr;
    if (root->val == x) return root;
    if (x < root->val) return find(root->left, x);
    else                return find(root->right, x);
}
```

### 插入

```cpp
Node* insert(Node* root, int x) {
    if (!root) return new Node{x, nullptr, nullptr};
    if (x < root->val) root->left = insert(root->left, x);
    else if (x > root->val) root->right = insert(root->right, x);
    return root;
}
```

### 中序遍历有序

对 BST 进行**中序遍历**，得到的序列是从小到大有序的，这是重要性质。

> 极端情况下 BST 会退化成链表，复杂度变为 O(n)，于是引入平衡二叉树（如 AVL）。


---

# 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/data-structures/binary-search-tree.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.
