> 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-tree.md).

# 二叉树

### 基本概念

二叉树是每个结点最多有两个子结点的树，分**左子树**和**右子树**，顺序不能互换。

* **根结点**：最上层结点
* **叶子结点**：没有子结点
* **深度 / 高度**：结点所在层数 / 树的最大层数

### 常见性质

* 第 i 层最多有 `2^(i-1)` 个结点
* 深度为 k 的二叉树最多有 `2^k - 1` 个结点
* 叶子数 n0 与度数为 2 的结点数 n2 满足：`n0 = n2 + 1`

### 存储方式

**顺序存储**（适合完全二叉树）：下标从 1 开始，结点 i 的左孩子为 `2i`，右孩子为 `2i+1`，父结点为 `i/2`。

**链式存储**：

```cpp
struct Node {
    int val;
    Node *left, *right;
    Node(int v) : val(v), left(nullptr), right(nullptr) {}
};
```

### 遍历方式

* **先序**：根 → 左 → 右
* **中序**：左 → 根 → 右
* **后序**：左 → 右 → 根
* **层序**：逐层从左到右（借助队列）

```cpp
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; }
```


---

# 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-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.
