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

# 树

### 树的基本概念

树是一种**非线性**的层次结构。由 n（n≥0）个结点组成的有限集合：

* **根结点**：没有父结点的唯一结点
* **子树**：某结点及其所有后代构成的集合
* **叶子结点**：没有子结点的结点
* **结点的度**：该结点子树的个数
* **树的度**：所有结点度的最大值
* **层次 / 深度**：根为第 1 层，树中最大层次为树的深度

### 二叉树

每个结点最多两个孩子，分**左子树**和**右子树**，顺序不可交换。

常见形态：满二叉树、完全二叉树、斜树。

### 重要性质

* 第 i 层最多 `2^(i-1)` 个结点
* 深度为 k 的二叉树最多 `2^k - 1` 个结点
* 叶子数 `n0 = n2 + 1`（n2 为度为 2 的结点数）
* n 个结点的完全二叉树深度为 `⌊log₂n⌋ + 1`

### 存储方式

* **顺序存储**：用数组，结点 i 的孩子为 2i、2i+1（适合完全二叉树）
* **链式存储**：结点的左右孩子用指针

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

### 树的遍历

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

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

> 相关：二叉树、完全二叉树、二叉排序树、哈夫曼树，见「数据结构」分组其它页面。


---

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