mirror of
https://github.com/krahets/hello-algo.git
synced 2026-04-04 11:10:21 +08:00
feat: Revised the book (#978)
* Sync recent changes to the revised Word. * Revised the preface chapter * Revised the introduction chapter * Revised the computation complexity chapter * Revised the chapter data structure * Revised the chapter array and linked list * Revised the chapter stack and queue * Revised the chapter hashing * Revised the chapter tree * Revised the chapter heap * Revised the chapter graph * Revised the chapter searching * Reivised the sorting chapter * Revised the divide and conquer chapter * Revised the chapter backtacking * Revised the DP chapter * Revised the greedy chapter * Revised the appendix chapter * Revised the preface chapter doubly * Revised the figures
This commit is contained in:
@@ -1,14 +1,14 @@
|
||||
# 二叉树数组表示
|
||||
|
||||
在链表表示下,二叉树的存储单元为节点 `TreeNode` ,节点之间通过指针相连接。在上节中,我们学习了在链表表示下的二叉树的各项基本操作。
|
||||
在链表表示下,二叉树的存储单元为节点 `TreeNode` ,节点之间通过指针相连接。上一节介绍了链表表示下的二叉树的各项基本操作。
|
||||
|
||||
那么,我们能否用数组来表示二叉树呢?答案是肯定的。
|
||||
|
||||
## 表示完美二叉树
|
||||
|
||||
先分析一个简单案例。给定一个完美二叉树,我们将所有节点按照层序遍历的顺序存储在一个数组中,则每个节点都对应唯一的数组索引。
|
||||
先分析一个简单案例。给定一棵完美二叉树,我们将所有节点按照层序遍历的顺序存储在一个数组中,则每个节点都对应唯一的数组索引。
|
||||
|
||||
根据层序遍历的特性,我们可以推导出父节点索引与子节点索引之间的“映射公式”:**若节点的索引为 $i$ ,则该节点的左子节点索引为 $2i + 1$ ,右子节点索引为 $2i + 2$** 。下图展示了各个节点索引之间的映射关系。
|
||||
根据层序遍历的特性,我们可以推导出父节点索引与子节点索引之间的“映射公式”:**若某节点的索引为 $i$ ,则该节点的左子节点索引为 $2i + 1$ ,右子节点索引为 $2i + 2$** 。下图展示了各个节点索引之间的映射关系。
|
||||
|
||||

|
||||
|
||||
@@ -18,11 +18,11 @@
|
||||
|
||||
完美二叉树是一个特例,在二叉树的中间层通常存在许多 $\text{None}$ 。由于层序遍历序列并不包含这些 $\text{None}$ ,因此我们无法仅凭该序列来推测 $\text{None}$ 的数量和分布位置。**这意味着存在多种二叉树结构都符合该层序遍历序列**。
|
||||
|
||||
如下图所示,给定一个非完美二叉树,上述的数组表示方法已经失效。
|
||||
如下图所示,给定一棵非完美二叉树,上述数组表示方法已经失效。
|
||||
|
||||

|
||||
|
||||
为了解决此问题,**我们可以考虑在层序遍历序列中显式地写出所有 $\text{None}$** 。如下图所示,这样处理后,层序遍历序列就可以唯一表示二叉树了。
|
||||
为了解决此问题,**我们可以考虑在层序遍历序列中显式地写出所有 $\text{None}$** 。如下图所示,这样处理后,层序遍历序列就可以唯一表示二叉树了。示例代码如下:
|
||||
|
||||
=== "Python"
|
||||
|
||||
@@ -126,7 +126,7 @@
|
||||
|
||||

|
||||
|
||||
以下代码实现了一个基于数组表示的二叉树,包括以下几种操作。
|
||||
以下代码实现了一棵基于数组表示的二叉树,包括以下几种操作。
|
||||
|
||||
- 给定某节点,获取它的值、左(右)子节点、父节点。
|
||||
- 获取前序遍历、中序遍历、后序遍历、层序遍历序列。
|
||||
@@ -135,7 +135,7 @@
|
||||
[file]{array_binary_tree}-[class]{array_binary_tree}-[func]{}
|
||||
```
|
||||
|
||||
## 优势与局限性
|
||||
## 优点与局限性
|
||||
|
||||
二叉树的数组表示主要有以下优点。
|
||||
|
||||
|
||||
Reference in New Issue
Block a user