Move docs/* to docs/zh/*
Before Width: | Height: | Size: 90 KiB |
Before Width: | Height: | Size: 68 KiB |
Before Width: | Height: | Size: 77 KiB |
Before Width: | Height: | Size: 68 KiB |
@ -1,218 +0,0 @@
|
||||
# 二叉树数组表示
|
||||
|
||||
在链表表示下,二叉树的存储单元为节点 `TreeNode` ,节点之间通过指针相连接。在上节中,我们学习了在链表表示下的二叉树的各项基本操作。
|
||||
|
||||
那么,我们能否用数组来表示二叉树呢?答案是肯定的。
|
||||
|
||||
## 表示完美二叉树
|
||||
|
||||
先分析一个简单案例。给定一个完美二叉树,我们将所有节点按照层序遍历的顺序存储在一个数组中,则每个节点都对应唯一的数组索引。
|
||||
|
||||
根据层序遍历的特性,我们可以推导出父节点索引与子节点索引之间的“映射公式”:**若节点的索引为 $i$ ,则该节点的左子节点索引为 $2i + 1$ ,右子节点索引为 $2i + 2$** 。下图展示了各个节点索引之间的映射关系。
|
||||
|
||||

|
||||
|
||||
**映射公式的角色相当于链表中的指针**。给定数组中的任意一个节点,我们都可以通过映射公式来访问它的左(右)子节点。
|
||||
|
||||
## 表示任意二叉树
|
||||
|
||||
完美二叉树是一个特例,在二叉树的中间层通常存在许多 $\text{None}$ 。由于层序遍历序列并不包含这些 $\text{None}$ ,因此我们无法仅凭该序列来推测 $\text{None}$ 的数量和分布位置。**这意味着存在多种二叉树结构都符合该层序遍历序列**。
|
||||
|
||||
如下图所示,给定一个非完美二叉树,上述的数组表示方法已经失效。
|
||||
|
||||

|
||||
|
||||
为了解决此问题,**我们可以考虑在层序遍历序列中显式地写出所有 $\text{None}$** 。如下图所示,这样处理后,层序遍历序列就可以唯一表示二叉树了。
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title=""
|
||||
# 二叉树的数组表示
|
||||
# 使用 None 来表示空位
|
||||
tree = [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15]
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title=""
|
||||
/* 二叉树的数组表示 */
|
||||
// 使用 int 最大值 INT_MAX 标记空位
|
||||
vector<int> tree = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15};
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title=""
|
||||
/* 二叉树的数组表示 */
|
||||
// 使用 int 的包装类 Integer ,就可以使用 null 来标记空位
|
||||
Integer[] tree = { 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 };
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title=""
|
||||
/* 二叉树的数组表示 */
|
||||
// 使用 int? 可空类型 ,就可以使用 null 来标记空位
|
||||
int?[] tree = { 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 };
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title=""
|
||||
/* 二叉树的数组表示 */
|
||||
// 使用 any 类型的切片, 就可以使用 nil 来标记空位
|
||||
tree := []any{1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title=""
|
||||
/* 二叉树的数组表示 */
|
||||
// 使用 Int? 可空类型 ,就可以使用 nil 来标记空位
|
||||
let tree: [Int?] = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15]
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title=""
|
||||
/* 二叉树的数组表示 */
|
||||
// 使用 null 来表示空位
|
||||
let tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15];
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title=""
|
||||
/* 二叉树的数组表示 */
|
||||
// 使用 null 来表示空位
|
||||
let tree: (number | null)[] = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15];
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title=""
|
||||
/* 二叉树的数组表示 */
|
||||
// 使用 int? 可空类型 ,就可以使用 null 来标记空位
|
||||
List<int?> tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15];
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title=""
|
||||
/* 二叉树的数组表示 */
|
||||
// 使用 None 来标记空位
|
||||
let tree = [Some(1), Some(2), Some(3), Some(4), None, Some(6), Some(7), Some(8), Some(9), None, None, Some(12), None, None, Some(15)];
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title=""
|
||||
/* 二叉树的数组表示 */
|
||||
// 使用 int 最大值标记空位,因此要求节点值不能为 INT_MAX
|
||||
int tree[] = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15};
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title=""
|
||||
|
||||
```
|
||||
|
||||

|
||||
|
||||
值得说明的是,**完全二叉树非常适合使用数组来表示**。回顾完全二叉树的定义,$\text{None}$ 只出现在最底层且靠右的位置,**因此所有 $\text{None}$ 一定出现在层序遍历序列的末尾**。
|
||||
|
||||
这意味着使用数组表示完全二叉树时,可以省略存储所有 $\text{None}$ ,非常方便。下图给出了一个例子。
|
||||
|
||||

|
||||
|
||||
以下代码实现了一个基于数组表示的二叉树,包括以下几种操作。
|
||||
|
||||
- 给定某节点,获取它的值、左(右)子节点、父节点。
|
||||
- 获取前序遍历、中序遍历、后序遍历、层序遍历序列。
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="array_binary_tree.py"
|
||||
[class]{ArrayBinaryTree}-[func]{}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="array_binary_tree.cpp"
|
||||
[class]{ArrayBinaryTree}-[func]{}
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="array_binary_tree.java"
|
||||
[class]{ArrayBinaryTree}-[func]{}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="array_binary_tree.cs"
|
||||
[class]{ArrayBinaryTree}-[func]{}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="array_binary_tree.go"
|
||||
[class]{arrayBinaryTree}-[func]{}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="array_binary_tree.swift"
|
||||
[class]{ArrayBinaryTree}-[func]{}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="array_binary_tree.js"
|
||||
[class]{ArrayBinaryTree}-[func]{}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title="array_binary_tree.ts"
|
||||
[class]{ArrayBinaryTree}-[func]{}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="array_binary_tree.dart"
|
||||
[class]{ArrayBinaryTree}-[func]{}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="array_binary_tree.rs"
|
||||
[class]{ArrayBinaryTree}-[func]{}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="array_binary_tree.c"
|
||||
[class]{arrayBinaryTree}-[func]{}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="array_binary_tree.zig"
|
||||
[class]{ArrayBinaryTree}-[func]{}
|
||||
```
|
||||
|
||||
## 优势与局限性
|
||||
|
||||
二叉树的数组表示主要有以下优点。
|
||||
|
||||
- 数组存储在连续的内存空间中,对缓存友好,访问与遍历速度较快。
|
||||
- 不需要存储指针,比较节省空间。
|
||||
- 允许随机访问节点。
|
||||
|
||||
然而,数组表示也存在一些局限性。
|
||||
|
||||
- 数组存储需要连续内存空间,因此不适合存储数据量过大的树。
|
||||
- 增删节点需要通过数组插入与删除操作实现,效率较低。
|
||||
- 当二叉树中存在大量 $\text{None}$ 时,数组中包含的节点数据比重较低,空间利用率较低。
|
Before Width: | Height: | Size: 55 KiB |
Before Width: | Height: | Size: 56 KiB |
Before Width: | Height: | Size: 71 KiB |
Before Width: | Height: | Size: 71 KiB |
Before Width: | Height: | Size: 83 KiB |
Before Width: | Height: | Size: 74 KiB |
Before Width: | Height: | Size: 42 KiB |
Before Width: | Height: | Size: 54 KiB |
Before Width: | Height: | Size: 59 KiB |
Before Width: | Height: | Size: 70 KiB |
Before Width: | Height: | Size: 84 KiB |
Before Width: | Height: | Size: 65 KiB |
@ -1,887 +0,0 @@
|
||||
# AVL 树 *
|
||||
|
||||
在二叉搜索树章节中,我们提到了在多次插入和删除操作后,二叉搜索树可能退化为链表。这种情况下,所有操作的时间复杂度将从 $O(\log n)$ 恶化为 $O(n)$ 。
|
||||
|
||||
如下图所示,经过两次删除节点操作,这个二叉搜索树便会退化为链表。
|
||||
|
||||

|
||||
|
||||
再例如,在下图的完美二叉树中插入两个节点后,树将严重向左倾斜,查找操作的时间复杂度也随之恶化。
|
||||
|
||||

|
||||
|
||||
G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorithm for the organization of information" 中提出了「AVL 树」。论文中详细描述了一系列操作,确保在持续添加和删除节点后,AVL 树不会退化,从而使得各种操作的时间复杂度保持在 $O(\log n)$ 级别。换句话说,在需要频繁进行增删查改操作的场景中,AVL 树能始终保持高效的数据操作性能,具有很好的应用价值。
|
||||
|
||||
## AVL 树常见术语
|
||||
|
||||
AVL 树既是二叉搜索树也是平衡二叉树,同时满足这两类二叉树的所有性质,因此也被称为「平衡二叉搜索树 balanced binary search tree」。
|
||||
|
||||
### 节点高度
|
||||
|
||||
由于 AVL 树的相关操作需要获取节点高度,因此我们需要为节点类添加 `height` 变量。
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title=""
|
||||
class TreeNode:
|
||||
"""AVL 树节点类"""
|
||||
def __init__(self, val: int):
|
||||
self.val: int = val # 节点值
|
||||
self.height: int = 0 # 节点高度
|
||||
self.left: TreeNode | None = None # 左子节点引用
|
||||
self.right: TreeNode | None = None # 右子节点引用
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title=""
|
||||
/* AVL 树节点类 */
|
||||
struct TreeNode {
|
||||
int val{}; // 节点值
|
||||
int height = 0; // 节点高度
|
||||
TreeNode *left{}; // 左子节点
|
||||
TreeNode *right{}; // 右子节点
|
||||
TreeNode() = default;
|
||||
explicit TreeNode(int x) : val(x){}
|
||||
};
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title=""
|
||||
/* AVL 树节点类 */
|
||||
class TreeNode {
|
||||
public int val; // 节点值
|
||||
public int height; // 节点高度
|
||||
public TreeNode left; // 左子节点
|
||||
public TreeNode right; // 右子节点
|
||||
public TreeNode(int x) { val = x; }
|
||||
}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title=""
|
||||
/* AVL 树节点类 */
|
||||
class TreeNode {
|
||||
public int val; // 节点值
|
||||
public int height; // 节点高度
|
||||
public TreeNode? left; // 左子节点
|
||||
public TreeNode? right; // 右子节点
|
||||
public TreeNode(int x) { val = x; }
|
||||
}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title=""
|
||||
/* AVL 树节点结构体 */
|
||||
type TreeNode struct {
|
||||
Val int // 节点值
|
||||
Height int // 节点高度
|
||||
Left *TreeNode // 左子节点引用
|
||||
Right *TreeNode // 右子节点引用
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title=""
|
||||
/* AVL 树节点类 */
|
||||
class TreeNode {
|
||||
var val: Int // 节点值
|
||||
var height: Int // 节点高度
|
||||
var left: TreeNode? // 左子节点
|
||||
var right: TreeNode? // 右子节点
|
||||
|
||||
init(x: Int) {
|
||||
val = x
|
||||
height = 0
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title=""
|
||||
/* AVL 树节点类 */
|
||||
class TreeNode {
|
||||
val; // 节点值
|
||||
height; //节点高度
|
||||
left; // 左子节点指针
|
||||
right; // 右子节点指针
|
||||
constructor(val, left, right, height) {
|
||||
this.val = val === undefined ? 0 : val;
|
||||
this.height = height === undefined ? 0 : height;
|
||||
this.left = left === undefined ? null : left;
|
||||
this.right = right === undefined ? null : right;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title=""
|
||||
/* AVL 树节点类 */
|
||||
class TreeNode {
|
||||
val: number; // 节点值
|
||||
height: number; // 节点高度
|
||||
left: TreeNode | null; // 左子节点指针
|
||||
right: TreeNode | null; // 右子节点指针
|
||||
constructor(val?: number, height?: number, left?: TreeNode | null, right?: TreeNode | null) {
|
||||
this.val = val === undefined ? 0 : val;
|
||||
this.height = height === undefined ? 0 : height;
|
||||
this.left = left === undefined ? null : left;
|
||||
this.right = right === undefined ? null : right;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title=""
|
||||
/* AVL 树节点类 */
|
||||
class TreeNode {
|
||||
int val; // 节点值
|
||||
int height; // 节点高度
|
||||
TreeNode? left; // 左子节点
|
||||
TreeNode? right; // 右子节点
|
||||
TreeNode(this.val, [this.height = 0, this.left, this.right]);
|
||||
}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title=""
|
||||
use std::rc::Rc;
|
||||
use std::cell::RefCell;
|
||||
|
||||
/* AVL 树节点结构体 */
|
||||
struct TreeNode {
|
||||
val: i32, // 节点值
|
||||
height: i32, // 节点高度
|
||||
left: Option<Rc<RefCell<TreeNode>>>, // 左子节点
|
||||
right: Option<Rc<RefCell<TreeNode>>>, // 右子节点
|
||||
}
|
||||
|
||||
impl TreeNode {
|
||||
/* 构造方法 */
|
||||
fn new(val: i32) -> Rc<RefCell<Self>> {
|
||||
Rc::new(RefCell::new(Self {
|
||||
val,
|
||||
height: 0,
|
||||
left: None,
|
||||
right: None
|
||||
}))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title=""
|
||||
/* AVL 树节点结构体 */
|
||||
struct TreeNode {
|
||||
int val;
|
||||
int height;
|
||||
struct TreeNode *left;
|
||||
struct TreeNode *right;
|
||||
};
|
||||
|
||||
typedef struct TreeNode TreeNode;
|
||||
|
||||
/* 构造函数 */
|
||||
TreeNode *newTreeNode(int val) {
|
||||
TreeNode *node;
|
||||
|
||||
node = (TreeNode *)malloc(sizeof(TreeNode));
|
||||
node->val = val;
|
||||
node->height = 0;
|
||||
node->left = NULL;
|
||||
node->right = NULL;
|
||||
return node;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title=""
|
||||
|
||||
```
|
||||
|
||||
“节点高度”是指从该节点到最远叶节点的距离,即所经过的“边”的数量。需要特别注意的是,叶节点的高度为 0 ,而空节点的高度为 -1 。我们将创建两个工具函数,分别用于获取和更新节点的高度。
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="avl_tree.py"
|
||||
[class]{AVLTree}-[func]{height}
|
||||
|
||||
[class]{AVLTree}-[func]{__update_height}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="avl_tree.cpp"
|
||||
[class]{AVLTree}-[func]{height}
|
||||
|
||||
[class]{AVLTree}-[func]{updateHeight}
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="avl_tree.java"
|
||||
[class]{AVLTree}-[func]{height}
|
||||
|
||||
[class]{AVLTree}-[func]{updateHeight}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="avl_tree.cs"
|
||||
[class]{AVLTree}-[func]{height}
|
||||
|
||||
[class]{AVLTree}-[func]{updateHeight}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="avl_tree.go"
|
||||
[class]{aVLTree}-[func]{height}
|
||||
|
||||
[class]{aVLTree}-[func]{updateHeight}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="avl_tree.swift"
|
||||
[class]{AVLTree}-[func]{height}
|
||||
|
||||
[class]{AVLTree}-[func]{updateHeight}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="avl_tree.js"
|
||||
[class]{AVLTree}-[func]{height}
|
||||
|
||||
[class]{AVLTree}-[func]{#updateHeight}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title="avl_tree.ts"
|
||||
[class]{AVLTree}-[func]{height}
|
||||
|
||||
[class]{AVLTree}-[func]{updateHeight}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="avl_tree.dart"
|
||||
[class]{AVLTree}-[func]{height}
|
||||
|
||||
[class]{AVLTree}-[func]{updateHeight}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="avl_tree.rs"
|
||||
[class]{AVLTree}-[func]{height}
|
||||
|
||||
[class]{AVLTree}-[func]{update_height}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="avl_tree.c"
|
||||
[class]{}-[func]{height}
|
||||
|
||||
[class]{}-[func]{updateHeight}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="avl_tree.zig"
|
||||
[class]{AVLTree}-[func]{height}
|
||||
|
||||
[class]{AVLTree}-[func]{updateHeight}
|
||||
```
|
||||
|
||||
### 节点平衡因子
|
||||
|
||||
节点的「平衡因子 balance factor」定义为节点左子树的高度减去右子树的高度,同时规定空节点的平衡因子为 0 。我们同样将获取节点平衡因子的功能封装成函数,方便后续使用。
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="avl_tree.py"
|
||||
[class]{AVLTree}-[func]{balance_factor}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="avl_tree.cpp"
|
||||
[class]{AVLTree}-[func]{balanceFactor}
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="avl_tree.java"
|
||||
[class]{AVLTree}-[func]{balanceFactor}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="avl_tree.cs"
|
||||
[class]{AVLTree}-[func]{balanceFactor}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="avl_tree.go"
|
||||
[class]{aVLTree}-[func]{balanceFactor}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="avl_tree.swift"
|
||||
[class]{AVLTree}-[func]{balanceFactor}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="avl_tree.js"
|
||||
[class]{AVLTree}-[func]{balanceFactor}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title="avl_tree.ts"
|
||||
[class]{AVLTree}-[func]{balanceFactor}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="avl_tree.dart"
|
||||
[class]{AVLTree}-[func]{balanceFactor}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="avl_tree.rs"
|
||||
[class]{AVLTree}-[func]{balance_factor}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="avl_tree.c"
|
||||
[class]{}-[func]{balanceFactor}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="avl_tree.zig"
|
||||
[class]{AVLTree}-[func]{balanceFactor}
|
||||
```
|
||||
|
||||
!!! note
|
||||
|
||||
设平衡因子为 $f$ ,则一棵 AVL 树的任意节点的平衡因子皆满足 $-1 \le f \le 1$ 。
|
||||
|
||||
## AVL 树旋转
|
||||
|
||||
AVL 树的特点在于“旋转”操作,它能够在不影响二叉树的中序遍历序列的前提下,使失衡节点重新恢复平衡。换句话说,**旋转操作既能保持“二叉搜索树”的性质,也能使树重新变为“平衡二叉树”**。
|
||||
|
||||
我们将平衡因子绝对值 $> 1$ 的节点称为“失衡节点”。根据节点失衡情况的不同,旋转操作分为四种:右旋、左旋、先右旋后左旋、先左旋后右旋。下面我们将详细介绍这些旋转操作。
|
||||
|
||||
### 右旋
|
||||
|
||||
如下图所示,节点下方为平衡因子。从底至顶看,二叉树中首个失衡节点是“节点 3”。我们关注以该失衡节点为根节点的子树,将该节点记为 `node` ,其左子节点记为 `child` ,执行“右旋”操作。完成右旋后,子树已经恢复平衡,并且仍然保持二叉搜索树的特性。
|
||||
|
||||
=== "<1>"
|
||||

|
||||
|
||||
=== "<2>"
|
||||

|
||||
|
||||
=== "<3>"
|
||||

|
||||
|
||||
=== "<4>"
|
||||

|
||||
|
||||
如下图所示,当节点 `child` 有右子节点(记为 `grandChild` )时,需要在右旋中添加一步:将 `grandChild` 作为 `node` 的左子节点。
|
||||
|
||||

|
||||
|
||||
“向右旋转”是一种形象化的说法,实际上需要通过修改节点指针来实现,代码如下所示。
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="avl_tree.py"
|
||||
[class]{AVLTree}-[func]{__right_rotate}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="avl_tree.cpp"
|
||||
[class]{AVLTree}-[func]{rightRotate}
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="avl_tree.java"
|
||||
[class]{AVLTree}-[func]{rightRotate}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="avl_tree.cs"
|
||||
[class]{AVLTree}-[func]{rightRotate}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="avl_tree.go"
|
||||
[class]{aVLTree}-[func]{rightRotate}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="avl_tree.swift"
|
||||
[class]{AVLTree}-[func]{rightRotate}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="avl_tree.js"
|
||||
[class]{AVLTree}-[func]{#rightRotate}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title="avl_tree.ts"
|
||||
[class]{AVLTree}-[func]{rightRotate}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="avl_tree.dart"
|
||||
[class]{AVLTree}-[func]{rightRotate}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="avl_tree.rs"
|
||||
[class]{AVLTree}-[func]{right_rotate}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="avl_tree.c"
|
||||
[class]{}-[func]{rightRotate}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="avl_tree.zig"
|
||||
[class]{AVLTree}-[func]{rightRotate}
|
||||
```
|
||||
|
||||
### 左旋
|
||||
|
||||
相应的,如果考虑上述失衡二叉树的“镜像”,则需要执行下图所示的“左旋”操作。
|
||||
|
||||

|
||||
|
||||
同理,如下图所示,当节点 `child` 有左子节点(记为 `grandChild` )时,需要在左旋中添加一步:将 `grandChild` 作为 `node` 的右子节点。
|
||||
|
||||

|
||||
|
||||
可以观察到,**右旋和左旋操作在逻辑上是镜像对称的,它们分别解决的两种失衡情况也是对称的**。基于对称性,我们只需将右旋的实现代码中的所有的 `left` 替换为 `right` ,将所有的 `right` 替换为 `left` ,即可得到左旋的实现代码。
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="avl_tree.py"
|
||||
[class]{AVLTree}-[func]{__left_rotate}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="avl_tree.cpp"
|
||||
[class]{AVLTree}-[func]{leftRotate}
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="avl_tree.java"
|
||||
[class]{AVLTree}-[func]{leftRotate}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="avl_tree.cs"
|
||||
[class]{AVLTree}-[func]{leftRotate}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="avl_tree.go"
|
||||
[class]{aVLTree}-[func]{leftRotate}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="avl_tree.swift"
|
||||
[class]{AVLTree}-[func]{leftRotate}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="avl_tree.js"
|
||||
[class]{AVLTree}-[func]{#leftRotate}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title="avl_tree.ts"
|
||||
[class]{AVLTree}-[func]{leftRotate}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="avl_tree.dart"
|
||||
[class]{AVLTree}-[func]{leftRotate}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="avl_tree.rs"
|
||||
[class]{AVLTree}-[func]{left_rotate}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="avl_tree.c"
|
||||
[class]{}-[func]{leftRotate}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="avl_tree.zig"
|
||||
[class]{AVLTree}-[func]{leftRotate}
|
||||
```
|
||||
|
||||
### 先左旋后右旋
|
||||
|
||||
对于下图中的失衡节点 3 ,仅使用左旋或右旋都无法使子树恢复平衡。此时需要先对 `child` 执行“左旋”,再对 `node` 执行“右旋”。
|
||||
|
||||

|
||||
|
||||
### 先右旋后左旋
|
||||
|
||||
如下图所示,对于上述失衡二叉树的镜像情况,需要先对 `child` 执行“右旋”,然后对 `node` 执行“左旋”。
|
||||
|
||||

|
||||
|
||||
### 旋转的选择
|
||||
|
||||
下图展示的四种失衡情况与上述案例逐个对应,分别需要采用右旋、左旋、先右后左、先左后右的旋转操作。
|
||||
|
||||

|
||||
|
||||
如下表所示,我们通过判断失衡节点的平衡因子以及较高一侧子节点的平衡因子的正负号,来确定失衡节点属于上图中的哪种情况。
|
||||
|
||||
<p align="center"> 表 <id> 四种旋转情况的选择条件 </p>
|
||||
|
||||
| 失衡节点的平衡因子 | 子节点的平衡因子 | 应采用的旋转方法 |
|
||||
| ---------------- | ---------------- | ---------------- |
|
||||
| $> 1$ (即左偏树) | $\geq 0$ | 右旋 |
|
||||
| $> 1$ (即左偏树) | $<0$ | 先左旋后右旋 |
|
||||
| $< -1$ (即右偏树) | $\leq 0$ | 左旋 |
|
||||
| $< -1$ (即右偏树) | $>0$ | 先右旋后左旋 |
|
||||
|
||||
为了便于使用,我们将旋转操作封装成一个函数。**有了这个函数,我们就能对各种失衡情况进行旋转,使失衡节点重新恢复平衡**。
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="avl_tree.py"
|
||||
[class]{AVLTree}-[func]{__rotate}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="avl_tree.cpp"
|
||||
[class]{AVLTree}-[func]{rotate}
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="avl_tree.java"
|
||||
[class]{AVLTree}-[func]{rotate}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="avl_tree.cs"
|
||||
[class]{AVLTree}-[func]{rotate}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="avl_tree.go"
|
||||
[class]{aVLTree}-[func]{rotate}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="avl_tree.swift"
|
||||
[class]{AVLTree}-[func]{rotate}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="avl_tree.js"
|
||||
[class]{AVLTree}-[func]{#rotate}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title="avl_tree.ts"
|
||||
[class]{AVLTree}-[func]{rotate}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="avl_tree.dart"
|
||||
[class]{AVLTree}-[func]{rotate}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="avl_tree.rs"
|
||||
[class]{AVLTree}-[func]{rotate}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="avl_tree.c"
|
||||
[class]{}-[func]{rotate}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="avl_tree.zig"
|
||||
[class]{AVLTree}-[func]{rotate}
|
||||
```
|
||||
|
||||
## AVL 树常用操作
|
||||
|
||||
### 插入节点
|
||||
|
||||
AVL 树的节点插入操作与二叉搜索树在主体上类似。唯一的区别在于,在 AVL 树中插入节点后,从该节点到根节点的路径上可能会出现一系列失衡节点。因此,**我们需要从这个节点开始,自底向上执行旋转操作,使所有失衡节点恢复平衡**。
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="avl_tree.py"
|
||||
[class]{AVLTree}-[func]{insert}
|
||||
|
||||
[class]{AVLTree}-[func]{__insert_helper}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="avl_tree.cpp"
|
||||
[class]{AVLTree}-[func]{insert}
|
||||
|
||||
[class]{AVLTree}-[func]{insertHelper}
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="avl_tree.java"
|
||||
[class]{AVLTree}-[func]{insert}
|
||||
|
||||
[class]{AVLTree}-[func]{insertHelper}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="avl_tree.cs"
|
||||
[class]{AVLTree}-[func]{insert}
|
||||
|
||||
[class]{AVLTree}-[func]{insertHelper}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="avl_tree.go"
|
||||
[class]{aVLTree}-[func]{insert}
|
||||
|
||||
[class]{aVLTree}-[func]{insertHelper}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="avl_tree.swift"
|
||||
[class]{AVLTree}-[func]{insert}
|
||||
|
||||
[class]{AVLTree}-[func]{insertHelper}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="avl_tree.js"
|
||||
[class]{AVLTree}-[func]{insert}
|
||||
|
||||
[class]{AVLTree}-[func]{#insertHelper}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title="avl_tree.ts"
|
||||
[class]{AVLTree}-[func]{insert}
|
||||
|
||||
[class]{AVLTree}-[func]{insertHelper}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="avl_tree.dart"
|
||||
[class]{AVLTree}-[func]{insert}
|
||||
|
||||
[class]{AVLTree}-[func]{insertHelper}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="avl_tree.rs"
|
||||
[class]{AVLTree}-[func]{insert}
|
||||
|
||||
[class]{AVLTree}-[func]{insert_helper}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="avl_tree.c"
|
||||
[class]{aVLTree}-[func]{insert}
|
||||
|
||||
[class]{}-[func]{insertHelper}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="avl_tree.zig"
|
||||
[class]{AVLTree}-[func]{insert}
|
||||
|
||||
[class]{AVLTree}-[func]{insertHelper}
|
||||
```
|
||||
|
||||
### 删除节点
|
||||
|
||||
类似地,在二叉搜索树的删除节点方法的基础上,需要从底至顶地执行旋转操作,使所有失衡节点恢复平衡。
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="avl_tree.py"
|
||||
[class]{AVLTree}-[func]{remove}
|
||||
|
||||
[class]{AVLTree}-[func]{__remove_helper}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="avl_tree.cpp"
|
||||
[class]{AVLTree}-[func]{remove}
|
||||
|
||||
[class]{AVLTree}-[func]{removeHelper}
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="avl_tree.java"
|
||||
[class]{AVLTree}-[func]{remove}
|
||||
|
||||
[class]{AVLTree}-[func]{removeHelper}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="avl_tree.cs"
|
||||
[class]{AVLTree}-[func]{remove}
|
||||
|
||||
[class]{AVLTree}-[func]{removeHelper}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="avl_tree.go"
|
||||
[class]{aVLTree}-[func]{remove}
|
||||
|
||||
[class]{aVLTree}-[func]{removeHelper}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="avl_tree.swift"
|
||||
[class]{AVLTree}-[func]{remove}
|
||||
|
||||
[class]{AVLTree}-[func]{removeHelper}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="avl_tree.js"
|
||||
[class]{AVLTree}-[func]{remove}
|
||||
|
||||
[class]{AVLTree}-[func]{#removeHelper}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title="avl_tree.ts"
|
||||
[class]{AVLTree}-[func]{remove}
|
||||
|
||||
[class]{AVLTree}-[func]{removeHelper}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="avl_tree.dart"
|
||||
[class]{AVLTree}-[func]{remove}
|
||||
|
||||
[class]{AVLTree}-[func]{removeHelper}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="avl_tree.rs"
|
||||
[class]{AVLTree}-[func]{remove}
|
||||
|
||||
[class]{AVLTree}-[func]{remove_helper}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="avl_tree.c"
|
||||
[class]{aVLTree}-[func]{removeNode}
|
||||
|
||||
[class]{}-[func]{removeHelper}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="avl_tree.zig"
|
||||
[class]{AVLTree}-[func]{remove}
|
||||
|
||||
[class]{AVLTree}-[func]{removeHelper}
|
||||
```
|
||||
|
||||
### 查找节点
|
||||
|
||||
AVL 树的节点查找操作与二叉搜索树一致,在此不再赘述。
|
||||
|
||||
## AVL 树典型应用
|
||||
|
||||
- 组织和存储大型数据,适用于高频查找、低频增删的场景。
|
||||
- 用于构建数据库中的索引系统。
|
||||
- 红黑树在许多应用中比 AVL 树更受欢迎。这是因为红黑树的平衡条件相对宽松,在红黑树中插入与删除节点所需的旋转操作相对较少,其节点增删操作的平均效率更高。
|
Before Width: | Height: | Size: 50 KiB |
Before Width: | Height: | Size: 61 KiB |
Before Width: | Height: | Size: 105 KiB |
Before Width: | Height: | Size: 87 KiB |
Before Width: | Height: | Size: 86 KiB |
Before Width: | Height: | Size: 88 KiB |
Before Width: | Height: | Size: 59 KiB |
Before Width: | Height: | Size: 81 KiB |
Before Width: | Height: | Size: 86 KiB |
Before Width: | Height: | Size: 92 KiB |
Before Width: | Height: | Size: 54 KiB |
Before Width: | Height: | Size: 55 KiB |
Before Width: | Height: | Size: 58 KiB |
Before Width: | Height: | Size: 58 KiB |
@ -1,337 +0,0 @@
|
||||
# 二叉搜索树
|
||||
|
||||
如下图所示,「二叉搜索树 binary search tree」满足以下条件。
|
||||
|
||||
1. 对于根节点,左子树中所有节点的值 $<$ 根节点的值 $<$ 右子树中所有节点的值。
|
||||
2. 任意节点的左、右子树也是二叉搜索树,即同样满足条件 `1.` 。
|
||||
|
||||

|
||||
|
||||
## 二叉搜索树的操作
|
||||
|
||||
我们将二叉搜索树封装为一个类 `ArrayBinaryTree` ,并声明一个成员变量 `root` ,指向树的根节点。
|
||||
|
||||
### 查找节点
|
||||
|
||||
给定目标节点值 `num` ,可以根据二叉搜索树的性质来查找。如下图所示,我们声明一个节点 `cur` ,从二叉树的根节点 `root` 出发,循环比较节点值 `cur.val` 和 `num` 之间的大小关系。
|
||||
|
||||
- 若 `cur.val < num` ,说明目标节点在 `cur` 的右子树中,因此执行 `cur = cur.right` 。
|
||||
- 若 `cur.val > num` ,说明目标节点在 `cur` 的左子树中,因此执行 `cur = cur.left` 。
|
||||
- 若 `cur.val = num` ,说明找到目标节点,跳出循环并返回该节点。
|
||||
|
||||
=== "<1>"
|
||||

|
||||
|
||||
=== "<2>"
|
||||

|
||||
|
||||
=== "<3>"
|
||||

|
||||
|
||||
=== "<4>"
|
||||

|
||||
|
||||
二叉搜索树的查找操作与二分查找算法的工作原理一致,都是每轮排除一半情况。循环次数最多为二叉树的高度,当二叉树平衡时,使用 $O(\log n)$ 时间。
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="binary_search_tree.py"
|
||||
[class]{BinarySearchTree}-[func]{search}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="binary_search_tree.cpp"
|
||||
[class]{BinarySearchTree}-[func]{search}
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="binary_search_tree.java"
|
||||
[class]{BinarySearchTree}-[func]{search}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="binary_search_tree.cs"
|
||||
[class]{BinarySearchTree}-[func]{search}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="binary_search_tree.go"
|
||||
[class]{binarySearchTree}-[func]{search}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="binary_search_tree.swift"
|
||||
[class]{BinarySearchTree}-[func]{search}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="binary_search_tree.js"
|
||||
[class]{BinarySearchTree}-[func]{search}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title="binary_search_tree.ts"
|
||||
[class]{BinarySearchTree}-[func]{search}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="binary_search_tree.dart"
|
||||
[class]{BinarySearchTree}-[func]{search}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="binary_search_tree.rs"
|
||||
[class]{BinarySearchTree}-[func]{search}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="binary_search_tree.c"
|
||||
[class]{binarySearchTree}-[func]{search}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="binary_search_tree.zig"
|
||||
[class]{BinarySearchTree}-[func]{search}
|
||||
```
|
||||
|
||||
### 插入节点
|
||||
|
||||
给定一个待插入元素 `num` ,为了保持二叉搜索树“左子树 < 根节点 < 右子树”的性质,插入操作流程如下图所示。
|
||||
|
||||
1. **查找插入位置**:与查找操作相似,从根节点出发,根据当前节点值和 `num` 的大小关系循环向下搜索,直到越过叶节点(遍历至 $\text{None}$ )时跳出循环。
|
||||
2. **在该位置插入节点**:初始化节点 `num` ,将该节点置于 $\text{None}$ 的位置。
|
||||
|
||||

|
||||
|
||||
在代码实现中,需要注意以下两点。
|
||||
|
||||
- 二叉搜索树不允许存在重复节点,否则将违反其定义。因此,若待插入节点在树中已存在,则不执行插入,直接返回。
|
||||
- 为了实现插入节点,我们需要借助节点 `pre` 保存上一轮循环的节点。这样在遍历至 $\text{None}$ 时,我们可以获取到其父节点,从而完成节点插入操作。
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="binary_search_tree.py"
|
||||
[class]{BinarySearchTree}-[func]{insert}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="binary_search_tree.cpp"
|
||||
[class]{BinarySearchTree}-[func]{insert}
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="binary_search_tree.java"
|
||||
[class]{BinarySearchTree}-[func]{insert}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="binary_search_tree.cs"
|
||||
[class]{BinarySearchTree}-[func]{insert}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="binary_search_tree.go"
|
||||
[class]{binarySearchTree}-[func]{insert}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="binary_search_tree.swift"
|
||||
[class]{BinarySearchTree}-[func]{insert}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="binary_search_tree.js"
|
||||
[class]{BinarySearchTree}-[func]{insert}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title="binary_search_tree.ts"
|
||||
[class]{BinarySearchTree}-[func]{insert}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="binary_search_tree.dart"
|
||||
[class]{BinarySearchTree}-[func]{insert}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="binary_search_tree.rs"
|
||||
[class]{BinarySearchTree}-[func]{insert}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="binary_search_tree.c"
|
||||
[class]{binarySearchTree}-[func]{insert}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="binary_search_tree.zig"
|
||||
[class]{BinarySearchTree}-[func]{insert}
|
||||
```
|
||||
|
||||
与查找节点相同,插入节点使用 $O(\log n)$ 时间。
|
||||
|
||||
### 删除节点
|
||||
|
||||
先在二叉树中查找到目标节点,再将其从二叉树中删除。
|
||||
|
||||
与插入节点类似,我们需要保证在删除操作完成后,二叉搜索树的“左子树 < 根节点 < 右子树”的性质仍然满足。
|
||||
|
||||
因此,我们需要根据目标节点的子节点数量,共分为 0、1 和 2 这三种情况,执行对应的删除节点操作。
|
||||
|
||||
如下图所示,当待删除节点的度为 $0$ 时,表示该节点是叶节点,可以直接删除。
|
||||
|
||||

|
||||
|
||||
如下图所示,当待删除节点的度为 $1$ 时,将待删除节点替换为其子节点即可。
|
||||
|
||||

|
||||
|
||||
当待删除节点的度为 $2$ 时,我们无法直接删除它,而需要使用一个节点替换该节点。由于要保持二叉搜索树“左 $<$ 根 $<$ 右”的性质,**因此这个节点可以是右子树的最小节点或左子树的最大节点**。
|
||||
|
||||
假设我们选择右子树的最小节点(即中序遍历的下一个节点),则删除操作流程如下图所示。
|
||||
|
||||
1. 找到待删除节点在“中序遍历序列”中的下一个节点,记为 `tmp` 。
|
||||
2. 将 `tmp` 的值覆盖待删除节点的值,并在树中递归删除节点 `tmp` 。
|
||||
|
||||
=== "<1>"
|
||||

|
||||
|
||||
=== "<2>"
|
||||

|
||||
|
||||
=== "<3>"
|
||||

|
||||
|
||||
=== "<4>"
|
||||

|
||||
|
||||
删除节点操作同样使用 $O(\log n)$ 时间,其中查找待删除节点需要 $O(\log n)$ 时间,获取中序遍历后继节点需要 $O(\log n)$ 时间。
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="binary_search_tree.py"
|
||||
[class]{BinarySearchTree}-[func]{remove}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="binary_search_tree.cpp"
|
||||
[class]{BinarySearchTree}-[func]{remove}
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="binary_search_tree.java"
|
||||
[class]{BinarySearchTree}-[func]{remove}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="binary_search_tree.cs"
|
||||
[class]{BinarySearchTree}-[func]{remove}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="binary_search_tree.go"
|
||||
[class]{binarySearchTree}-[func]{remove}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="binary_search_tree.swift"
|
||||
[class]{BinarySearchTree}-[func]{remove}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="binary_search_tree.js"
|
||||
[class]{BinarySearchTree}-[func]{remove}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title="binary_search_tree.ts"
|
||||
[class]{BinarySearchTree}-[func]{remove}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="binary_search_tree.dart"
|
||||
[class]{BinarySearchTree}-[func]{remove}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="binary_search_tree.rs"
|
||||
[class]{BinarySearchTree}-[func]{remove}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="binary_search_tree.c"
|
||||
[class]{binarySearchTree}-[func]{removeNode}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="binary_search_tree.zig"
|
||||
[class]{BinarySearchTree}-[func]{remove}
|
||||
```
|
||||
|
||||
### 中序遍历有序
|
||||
|
||||
如下图所示,二叉树的中序遍历遵循“左 $\rightarrow$ 根 $\rightarrow$ 右”的遍历顺序,而二叉搜索树满足“左子节点 $<$ 根节点 $<$ 右子节点”的大小关系。
|
||||
|
||||
这意味着在二叉搜索树中进行中序遍历时,总是会优先遍历下一个最小节点,从而得出一个重要性质:**二叉搜索树的中序遍历序列是升序的**。
|
||||
|
||||
利用中序遍历升序的性质,我们在二叉搜索树中获取有序数据仅需 $O(n)$ 时间,无须进行额外的排序操作,非常高效。
|
||||
|
||||

|
||||
|
||||
## 二叉搜索树的效率
|
||||
|
||||
给定一组数据,我们考虑使用数组或二叉搜索树存储。观察下表,二叉搜索树的各项操作的时间复杂度都是对数阶,具有稳定且高效的性能表现。只有在高频添加、低频查找删除的数据适用场景下,数组比二叉搜索树的效率更高。
|
||||
|
||||
<p align="center"> 表 <id> 数组与搜索树的效率对比 </p>
|
||||
|
||||
| | 无序数组 | 二叉搜索树 |
|
||||
| -------- | -------- | ----------- |
|
||||
| 查找元素 | $O(n)$ | $O(\log n)$ |
|
||||
| 插入元素 | $O(1)$ | $O(\log n)$ |
|
||||
| 删除元素 | $O(n)$ | $O(\log n)$ |
|
||||
|
||||
在理想情况下,二叉搜索树是“平衡”的,这样就可以在 $\log n$ 轮循环内查找任意节点。
|
||||
|
||||
然而,如果我们在二叉搜索树中不断地插入和删除节点,可能导致二叉树退化为下图所示的链表,这时各种操作的时间复杂度也会退化为 $O(n)$ 。
|
||||
|
||||

|
||||
|
||||
## 二叉搜索树常见应用
|
||||
|
||||
- 用作系统中的多级索引,实现高效的查找、插入、删除操作。
|
||||
- 作为某些搜索算法的底层数据结构。
|
||||
- 用于存储数据流,以保持其有序状态。
|
Before Width: | Height: | Size: 56 KiB |
Before Width: | Height: | Size: 71 KiB |
Before Width: | Height: | Size: 64 KiB |
Before Width: | Height: | Size: 75 KiB |
Before Width: | Height: | Size: 67 KiB |
Before Width: | Height: | Size: 52 KiB |
Before Width: | Height: | Size: 45 KiB |
Before Width: | Height: | Size: 56 KiB |
@ -1,602 +0,0 @@
|
||||
# 二叉树
|
||||
|
||||
「二叉树 binary tree」是一种非线性数据结构,代表着祖先与后代之间的派生关系,体现着“一分为二”的分治逻辑。与链表类似,二叉树的基本单元是节点,每个节点包含:值、左子节点引用、右子节点引用。
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title=""
|
||||
class TreeNode:
|
||||
"""二叉树节点类"""
|
||||
def __init__(self, val: int):
|
||||
self.val: int = val # 节点值
|
||||
self.left: TreeNode | None = None # 左子节点引用
|
||||
self.right: TreeNode | None = None # 右子节点引用
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title=""
|
||||
/* 二叉树节点结构体 */
|
||||
struct TreeNode {
|
||||
int val; // 节点值
|
||||
TreeNode *left; // 左子节点指针
|
||||
TreeNode *right; // 右子节点指针
|
||||
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
|
||||
};
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title=""
|
||||
/* 二叉树节点类 */
|
||||
class TreeNode {
|
||||
int val; // 节点值
|
||||
TreeNode left; // 左子节点引用
|
||||
TreeNode right; // 右子节点引用
|
||||
TreeNode(int x) { val = x; }
|
||||
}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title=""
|
||||
/* 二叉树节点类 */
|
||||
class TreeNode {
|
||||
int val; // 节点值
|
||||
TreeNode? left; // 左子节点引用
|
||||
TreeNode? right; // 右子节点引用
|
||||
TreeNode(int x) { val = x; }
|
||||
}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title=""
|
||||
/* 二叉树节点结构体 */
|
||||
type TreeNode struct {
|
||||
Val int
|
||||
Left *TreeNode
|
||||
Right *TreeNode
|
||||
}
|
||||
/* 构造方法 */
|
||||
func NewTreeNode(v int) *TreeNode {
|
||||
return &TreeNode{
|
||||
Left: nil, // 左子节点指针
|
||||
Right: nil, // 右子节点指针
|
||||
Val: v, // 节点值
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title=""
|
||||
/* 二叉树节点类 */
|
||||
class TreeNode {
|
||||
var val: Int // 节点值
|
||||
var left: TreeNode? // 左子节点引用
|
||||
var right: TreeNode? // 右子节点引用
|
||||
|
||||
init(x: Int) {
|
||||
val = x
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title=""
|
||||
/* 二叉树节点类 */
|
||||
class TreeNode {
|
||||
val; // 节点值
|
||||
left; // 左子节点指针
|
||||
right; // 右子节点指针
|
||||
constructor(val, left, right) {
|
||||
this.val = val === undefined ? 0 : val;
|
||||
this.left = left === undefined ? null : left;
|
||||
this.right = right === undefined ? null : right;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title=""
|
||||
/* 二叉树节点类 */
|
||||
class TreeNode {
|
||||
val: number;
|
||||
left: TreeNode | null;
|
||||
right: TreeNode | null;
|
||||
|
||||
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
|
||||
this.val = val === undefined ? 0 : val; // 节点值
|
||||
this.left = left === undefined ? null : left; // 左子节点引用
|
||||
this.right = right === undefined ? null : right; // 右子节点引用
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title=""
|
||||
/* 二叉树节点类 */
|
||||
class TreeNode {
|
||||
int val; // 节点值
|
||||
TreeNode? left; // 左子节点引用
|
||||
TreeNode? right; // 右子节点引用
|
||||
TreeNode(this.val, [this.left, this.right]);
|
||||
}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title=""
|
||||
use std::rc::Rc;
|
||||
use std::cell::RefCell;
|
||||
|
||||
/* 二叉树节点结构体 */
|
||||
struct TreeNode {
|
||||
val: i32, // 节点值
|
||||
left: Option<Rc<RefCell<TreeNode>>>, // 左子节点引用
|
||||
right: Option<Rc<RefCell<TreeNode>>>, // 右子节点引用
|
||||
}
|
||||
|
||||
impl TreeNode {
|
||||
/* 构造方法 */
|
||||
fn new(val: i32) -> Rc<RefCell<Self>> {
|
||||
Rc::new(RefCell::new(Self {
|
||||
val,
|
||||
left: None,
|
||||
right: None
|
||||
}))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title=""
|
||||
/* 二叉树节点结构体 */
|
||||
struct TreeNode {
|
||||
int val; // 节点值
|
||||
int height; // 节点高度
|
||||
struct TreeNode *left; // 左子节点指针
|
||||
struct TreeNode *right; // 右子节点指针
|
||||
};
|
||||
|
||||
typedef struct TreeNode TreeNode;
|
||||
|
||||
/* 构造函数 */
|
||||
TreeNode *newTreeNode(int val) {
|
||||
TreeNode *node;
|
||||
|
||||
node = (TreeNode *)malloc(sizeof(TreeNode));
|
||||
node->val = val;
|
||||
node->height = 0;
|
||||
node->left = NULL;
|
||||
node->right = NULL;
|
||||
return node;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title=""
|
||||
|
||||
```
|
||||
|
||||
每个节点都有两个引用(指针),分别指向「左子节点 left-child node」和「右子节点 right-child node」,该节点被称为这两个子节点的「父节点 parent node」。当给定一个二叉树的节点时,我们将该节点的左子节点及其以下节点形成的树称为该节点的「左子树 left subtree」,同理可得「右子树 right subtree」。
|
||||
|
||||
**在二叉树中,除叶节点外,其他所有节点都包含子节点和非空子树**。如下图所示,如果将“节点 2”视为父节点,则其左子节点和右子节点分别是“节点 4”和“节点 5”,左子树是“节点 4 及其以下节点形成的树”,右子树是“节点 5 及其以下节点形成的树”。
|
||||
|
||||

|
||||
|
||||
## 二叉树常见术语
|
||||
|
||||
二叉树的常用术语如下图所示。
|
||||
|
||||
- 「根节点 root node」:位于二叉树顶层的节点,没有父节点。
|
||||
- 「叶节点 leaf node」:没有子节点的节点,其两个指针均指向 $\text{None}$ 。
|
||||
- 「边 edge」:连接两个节点的线段,即节点引用(指针)。
|
||||
- 节点所在的「层 level」:从顶至底递增,根节点所在层为 1 。
|
||||
- 节点的「度 degree」:节点的子节点的数量。在二叉树中,度的取值范围是 0、1、2 。
|
||||
- 二叉树的「高度 height」:从根节点到最远叶节点所经过的边的数量。
|
||||
- 节点的「深度 depth」:从根节点到该节点所经过的边的数量。
|
||||
- 节点的「高度 height」:从最远叶节点到该节点所经过的边的数量。
|
||||
|
||||

|
||||
|
||||
!!! tip
|
||||
|
||||
请注意,我们通常将“高度”和“深度”定义为“走过边的数量”,但有些题目或教材可能会将其定义为“走过节点的数量”。在这种情况下,高度和深度都需要加 1 。
|
||||
|
||||
## 二叉树基本操作
|
||||
|
||||
### 初始化二叉树
|
||||
|
||||
与链表类似,首先初始化节点,然后构建引用(指针)。
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="binary_tree.py"
|
||||
# 初始化二叉树
|
||||
# 初始化节点
|
||||
n1 = TreeNode(val=1)
|
||||
n2 = TreeNode(val=2)
|
||||
n3 = TreeNode(val=3)
|
||||
n4 = TreeNode(val=4)
|
||||
n5 = TreeNode(val=5)
|
||||
# 构建引用指向(即指针)
|
||||
n1.left = n2
|
||||
n1.right = n3
|
||||
n2.left = n4
|
||||
n2.right = n5
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="binary_tree.cpp"
|
||||
/* 初始化二叉树 */
|
||||
// 初始化节点
|
||||
TreeNode* n1 = new TreeNode(1);
|
||||
TreeNode* n2 = new TreeNode(2);
|
||||
TreeNode* n3 = new TreeNode(3);
|
||||
TreeNode* n4 = new TreeNode(4);
|
||||
TreeNode* n5 = new TreeNode(5);
|
||||
// 构建引用指向(即指针)
|
||||
n1->left = n2;
|
||||
n1->right = n3;
|
||||
n2->left = n4;
|
||||
n2->right = n5;
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="binary_tree.java"
|
||||
// 初始化节点
|
||||
TreeNode n1 = new TreeNode(1);
|
||||
TreeNode n2 = new TreeNode(2);
|
||||
TreeNode n3 = new TreeNode(3);
|
||||
TreeNode n4 = new TreeNode(4);
|
||||
TreeNode n5 = new TreeNode(5);
|
||||
// 构建引用指向(即指针)
|
||||
n1.left = n2;
|
||||
n1.right = n3;
|
||||
n2.left = n4;
|
||||
n2.right = n5;
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="binary_tree.cs"
|
||||
/* 初始化二叉树 */
|
||||
// 初始化节点
|
||||
TreeNode n1 = new TreeNode(1);
|
||||
TreeNode n2 = new TreeNode(2);
|
||||
TreeNode n3 = new TreeNode(3);
|
||||
TreeNode n4 = new TreeNode(4);
|
||||
TreeNode n5 = new TreeNode(5);
|
||||
// 构建引用指向(即指针)
|
||||
n1.left = n2;
|
||||
n1.right = n3;
|
||||
n2.left = n4;
|
||||
n2.right = n5;
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="binary_tree.go"
|
||||
/* 初始化二叉树 */
|
||||
// 初始化节点
|
||||
n1 := NewTreeNode(1)
|
||||
n2 := NewTreeNode(2)
|
||||
n3 := NewTreeNode(3)
|
||||
n4 := NewTreeNode(4)
|
||||
n5 := NewTreeNode(5)
|
||||
// 构建引用指向(即指针)
|
||||
n1.Left = n2
|
||||
n1.Right = n3
|
||||
n2.Left = n4
|
||||
n2.Right = n5
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="binary_tree.swift"
|
||||
// 初始化节点
|
||||
let n1 = TreeNode(x: 1)
|
||||
let n2 = TreeNode(x: 2)
|
||||
let n3 = TreeNode(x: 3)
|
||||
let n4 = TreeNode(x: 4)
|
||||
let n5 = TreeNode(x: 5)
|
||||
// 构建引用指向(即指针)
|
||||
n1.left = n2
|
||||
n1.right = n3
|
||||
n2.left = n4
|
||||
n2.right = n5
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="binary_tree.js"
|
||||
/* 初始化二叉树 */
|
||||
// 初始化节点
|
||||
let n1 = new TreeNode(1),
|
||||
n2 = new TreeNode(2),
|
||||
n3 = new TreeNode(3),
|
||||
n4 = new TreeNode(4),
|
||||
n5 = new TreeNode(5);
|
||||
// 构建引用指向(即指针)
|
||||
n1.left = n2;
|
||||
n1.right = n3;
|
||||
n2.left = n4;
|
||||
n2.right = n5;
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title="binary_tree.ts"
|
||||
/* 初始化二叉树 */
|
||||
// 初始化节点
|
||||
let n1 = new TreeNode(1),
|
||||
n2 = new TreeNode(2),
|
||||
n3 = new TreeNode(3),
|
||||
n4 = new TreeNode(4),
|
||||
n5 = new TreeNode(5);
|
||||
// 构建引用指向(即指针)
|
||||
n1.left = n2;
|
||||
n1.right = n3;
|
||||
n2.left = n4;
|
||||
n2.right = n5;
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="binary_tree.dart"
|
||||
/* 初始化二叉树 */
|
||||
// 初始化节点
|
||||
TreeNode n1 = new TreeNode(1);
|
||||
TreeNode n2 = new TreeNode(2);
|
||||
TreeNode n3 = new TreeNode(3);
|
||||
TreeNode n4 = new TreeNode(4);
|
||||
TreeNode n5 = new TreeNode(5);
|
||||
// 构建引用指向(即指针)
|
||||
n1.left = n2;
|
||||
n1.right = n3;
|
||||
n2.left = n4;
|
||||
n2.right = n5;
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="binary_tree.rs"
|
||||
// 初始化节点
|
||||
let n1 = TreeNode::new(1);
|
||||
let n2 = TreeNode::new(2);
|
||||
let n3 = TreeNode::new(3);
|
||||
let n4 = TreeNode::new(4);
|
||||
let n5 = TreeNode::new(5);
|
||||
// 构建引用指向(即指针)
|
||||
n1.borrow_mut().left = Some(n2.clone());
|
||||
n1.borrow_mut().right = Some(n3);
|
||||
n2.borrow_mut().left = Some(n4);
|
||||
n2.borrow_mut().right = Some(n5);
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="binary_tree.c"
|
||||
/* 初始化二叉树 */
|
||||
// 初始化节点
|
||||
TreeNode *n1 = newTreeNode(1);
|
||||
TreeNode *n2 = newTreeNode(2);
|
||||
TreeNode *n3 = newTreeNode(3);
|
||||
TreeNode *n4 = newTreeNode(4);
|
||||
TreeNode *n5 = newTreeNode(5);
|
||||
// 构建引用指向(即指针)
|
||||
n1->left = n2;
|
||||
n1->right = n3;
|
||||
n2->left = n4;
|
||||
n2->right = n5;
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="binary_tree.zig"
|
||||
|
||||
```
|
||||
|
||||
### 插入与删除节点
|
||||
|
||||
与链表类似,在二叉树中插入与删除节点可以通过修改指针来实现。下图给出了一个示例。
|
||||
|
||||

|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="binary_tree.py"
|
||||
# 插入与删除节点
|
||||
p = TreeNode(0)
|
||||
# 在 n1 -> n2 中间插入节点 P
|
||||
n1.left = p
|
||||
p.left = n2
|
||||
# 删除节点 P
|
||||
n1.left = n2
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="binary_tree.cpp"
|
||||
/* 插入与删除节点 */
|
||||
TreeNode* P = new TreeNode(0);
|
||||
// 在 n1 -> n2 中间插入节点 P
|
||||
n1->left = P;
|
||||
P->left = n2;
|
||||
// 删除节点 P
|
||||
n1->left = n2;
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="binary_tree.java"
|
||||
TreeNode P = new TreeNode(0);
|
||||
// 在 n1 -> n2 中间插入节点 P
|
||||
n1.left = P;
|
||||
P.left = n2;
|
||||
// 删除节点 P
|
||||
n1.left = n2;
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="binary_tree.cs"
|
||||
/* 插入与删除节点 */
|
||||
TreeNode P = new TreeNode(0);
|
||||
// 在 n1 -> n2 中间插入节点 P
|
||||
n1.left = P;
|
||||
P.left = n2;
|
||||
// 删除节点 P
|
||||
n1.left = n2;
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="binary_tree.go"
|
||||
/* 插入与删除节点 */
|
||||
// 在 n1 -> n2 中间插入节点 P
|
||||
p := NewTreeNode(0)
|
||||
n1.Left = p
|
||||
p.Left = n2
|
||||
// 删除节点 P
|
||||
n1.Left = n2
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="binary_tree.swift"
|
||||
let P = TreeNode(x: 0)
|
||||
// 在 n1 -> n2 中间插入节点 P
|
||||
n1.left = P
|
||||
P.left = n2
|
||||
// 删除节点 P
|
||||
n1.left = n2
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="binary_tree.js"
|
||||
/* 插入与删除节点 */
|
||||
let P = new TreeNode(0);
|
||||
// 在 n1 -> n2 中间插入节点 P
|
||||
n1.left = P;
|
||||
P.left = n2;
|
||||
// 删除节点 P
|
||||
n1.left = n2;
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title="binary_tree.ts"
|
||||
/* 插入与删除节点 */
|
||||
const P = new TreeNode(0);
|
||||
// 在 n1 -> n2 中间插入节点 P
|
||||
n1.left = P;
|
||||
P.left = n2;
|
||||
// 删除节点 P
|
||||
n1.left = n2;
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="binary_tree.dart"
|
||||
/* 插入与删除节点 */
|
||||
TreeNode P = new TreeNode(0);
|
||||
// 在 n1 -> n2 中间插入节点 P
|
||||
n1.left = P;
|
||||
P.left = n2;
|
||||
// 删除节点 P
|
||||
n1.left = n2;
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="binary_tree.rs"
|
||||
let p = TreeNode::new(0);
|
||||
// 在 n1 -> n2 中间插入节点 P
|
||||
n1.borrow_mut().left = Some(p.clone());
|
||||
p.borrow_mut().left = Some(n2.clone());
|
||||
// 删除节点 p
|
||||
n1.borrow_mut().left = Some(n2);
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="binary_tree.c"
|
||||
/* 插入与删除节点 */
|
||||
TreeNode *P = newTreeNode(0);
|
||||
// 在 n1 -> n2 中间插入节点 P
|
||||
n1->left = P;
|
||||
P->left = n2;
|
||||
// 删除节点 P
|
||||
n1->left = n2;
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="binary_tree.zig"
|
||||
|
||||
```
|
||||
|
||||
!!! note
|
||||
|
||||
需要注意的是,插入节点可能会改变二叉树的原有逻辑结构,而删除节点通常意味着删除该节点及其所有子树。因此,在二叉树中,插入与删除操作通常是由一套操作配合完成的,以实现有实际意义的操作。
|
||||
|
||||
## 常见二叉树类型
|
||||
|
||||
### 完美二叉树
|
||||
|
||||
「完美二叉树 perfect binary tree」所有层的节点都被完全填满。在完美二叉树中,叶节点的度为 $0$ ,其余所有节点的度都为 $2$ ;若树高度为 $h$ ,则节点总数为 $2^{h+1} - 1$ ,呈现标准的指数级关系,反映了自然界中常见的细胞分裂现象。
|
||||
|
||||
!!! tip
|
||||
|
||||
请注意,在中文社区中,完美二叉树常被称为「满二叉树」。
|
||||
|
||||

|
||||
|
||||
### 完全二叉树
|
||||
|
||||
如下图所示,「完全二叉树 complete binary tree」只有最底层的节点未被填满,且最底层节点尽量靠左填充。
|
||||
|
||||

|
||||
|
||||
### 完满二叉树
|
||||
|
||||
如下图所示,「完满二叉树 full binary tree」除了叶节点之外,其余所有节点都有两个子节点。
|
||||
|
||||

|
||||
|
||||
### 平衡二叉树
|
||||
|
||||
如下图所示,「平衡二叉树 balanced binary tree」中任意节点的左子树和右子树的高度之差的绝对值不超过 1 。
|
||||
|
||||

|
||||
|
||||
## 二叉树的退化
|
||||
|
||||
下图展示了二叉树的理想与退化状态。当二叉树的每层节点都被填满时,达到“完美二叉树”;而当所有节点都偏向一侧时,二叉树退化为“链表”。
|
||||
|
||||
- 完美二叉树是理想情况,可以充分发挥二叉树“分治”的优势。
|
||||
- 链表则是另一个极端,各项操作都变为线性操作,时间复杂度退化至 $O(n)$ 。
|
||||
|
||||

|
||||
|
||||
如下表所示,在最佳和最差结构下,二叉树的叶节点数量、节点总数、高度等达到极大或极小值。
|
||||
|
||||
<p align="center"> 表 <id> 二叉树的最佳与最差情况 </p>
|
||||
|
||||
| | 完美二叉树 | 链表 |
|
||||
| ----------------------------- | ---------- | ---------- |
|
||||
| 第 $i$ 层的节点数量 | $2^{i-1}$ | $1$ |
|
||||
| 高度 $h$ 树的叶节点数量 | $2^h$ | $1$ |
|
||||
| 高度 $h$ 树的节点总数 | $2^{h+1} - 1$ | $h + 1$ |
|
||||
| 节点总数 $n$ 树的高度 | $\log_2 (n+1) - 1$ | $n - 1$ |
|
Before Width: | Height: | Size: 59 KiB |
Before Width: | Height: | Size: 150 KiB |
Before Width: | Height: | Size: 57 KiB |
Before Width: | Height: | Size: 85 KiB |
Before Width: | Height: | Size: 91 KiB |
Before Width: | Height: | Size: 62 KiB |
Before Width: | Height: | Size: 64 KiB |
Before Width: | Height: | Size: 66 KiB |
Before Width: | Height: | Size: 70 KiB |
Before Width: | Height: | Size: 74 KiB |
Before Width: | Height: | Size: 78 KiB |
Before Width: | Height: | Size: 81 KiB |
Before Width: | Height: | Size: 82 KiB |
@ -1,273 +0,0 @@
|
||||
# 二叉树遍历
|
||||
|
||||
从物理结构的角度来看,树是一种基于链表的数据结构,因此其遍历方式是通过指针逐个访问节点。然而,树是一种非线性数据结构,这使得遍历树比遍历链表更加复杂,需要借助搜索算法来实现。
|
||||
|
||||
二叉树常见的遍历方式包括层序遍历、前序遍历、中序遍历和后序遍历等。
|
||||
|
||||
## 层序遍历
|
||||
|
||||
如下图所示,「层序遍历 level-order traversal」从顶部到底部逐层遍历二叉树,并在每一层按照从左到右的顺序访问节点。
|
||||
|
||||
层序遍历本质上属于「广度优先遍历 breadth-first traversal」,它体现了一种“一圈一圈向外扩展”的逐层遍历方式。
|
||||
|
||||

|
||||
|
||||
### 代码实现
|
||||
|
||||
广度优先遍历通常借助“队列”来实现。队列遵循“先进先出”的规则,而广度优先遍历则遵循“逐层推进”的规则,两者背后的思想是一致的。
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="binary_tree_bfs.py"
|
||||
[class]{}-[func]{level_order}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="binary_tree_bfs.cpp"
|
||||
[class]{}-[func]{levelOrder}
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="binary_tree_bfs.java"
|
||||
[class]{binary_tree_bfs}-[func]{levelOrder}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="binary_tree_bfs.cs"
|
||||
[class]{binary_tree_bfs}-[func]{levelOrder}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="binary_tree_bfs.go"
|
||||
[class]{}-[func]{levelOrder}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="binary_tree_bfs.swift"
|
||||
[class]{}-[func]{levelOrder}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="binary_tree_bfs.js"
|
||||
[class]{}-[func]{levelOrder}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title="binary_tree_bfs.ts"
|
||||
[class]{}-[func]{levelOrder}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="binary_tree_bfs.dart"
|
||||
[class]{}-[func]{levelOrder}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="binary_tree_bfs.rs"
|
||||
[class]{}-[func]{level_order}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="binary_tree_bfs.c"
|
||||
[class]{}-[func]{levelOrder}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="binary_tree_bfs.zig"
|
||||
[class]{}-[func]{levelOrder}
|
||||
```
|
||||
|
||||
### 复杂度分析
|
||||
|
||||
- **时间复杂度 $O(n)$** :所有节点被访问一次,使用 $O(n)$ 时间,其中 $n$ 为节点数量。
|
||||
- **空间复杂度 $O(n)$** :在最差情况下,即满二叉树时,遍历到最底层之前,队列中最多同时存在 $(n + 1) / 2$ 个节点,占用 $O(n)$ 空间。
|
||||
|
||||
## 前序、中序、后序遍历
|
||||
|
||||
相应地,前序、中序和后序遍历都属于「深度优先遍历 depth-first traversal」,它体现了一种“先走到尽头,再回溯继续”的遍历方式。
|
||||
|
||||
下图展示了对二叉树进行深度优先遍历的工作原理。**深度优先遍历就像是绕着整个二叉树的外围“走”一圈**,在每个节点都会遇到三个位置,分别对应前序遍历、中序遍历和后序遍历。
|
||||
|
||||

|
||||
|
||||
### 代码实现
|
||||
|
||||
深度优先搜索通常基于递归实现:
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="binary_tree_dfs.py"
|
||||
[class]{}-[func]{pre_order}
|
||||
|
||||
[class]{}-[func]{in_order}
|
||||
|
||||
[class]{}-[func]{post_order}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="binary_tree_dfs.cpp"
|
||||
[class]{}-[func]{preOrder}
|
||||
|
||||
[class]{}-[func]{inOrder}
|
||||
|
||||
[class]{}-[func]{postOrder}
|
||||
```
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="binary_tree_dfs.java"
|
||||
[class]{binary_tree_dfs}-[func]{preOrder}
|
||||
|
||||
[class]{binary_tree_dfs}-[func]{inOrder}
|
||||
|
||||
[class]{binary_tree_dfs}-[func]{postOrder}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="binary_tree_dfs.cs"
|
||||
[class]{binary_tree_dfs}-[func]{preOrder}
|
||||
|
||||
[class]{binary_tree_dfs}-[func]{inOrder}
|
||||
|
||||
[class]{binary_tree_dfs}-[func]{postOrder}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="binary_tree_dfs.go"
|
||||
[class]{}-[func]{preOrder}
|
||||
|
||||
[class]{}-[func]{inOrder}
|
||||
|
||||
[class]{}-[func]{postOrder}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="binary_tree_dfs.swift"
|
||||
[class]{}-[func]{preOrder}
|
||||
|
||||
[class]{}-[func]{inOrder}
|
||||
|
||||
[class]{}-[func]{postOrder}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="binary_tree_dfs.js"
|
||||
[class]{}-[func]{preOrder}
|
||||
|
||||
[class]{}-[func]{inOrder}
|
||||
|
||||
[class]{}-[func]{postOrder}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title="binary_tree_dfs.ts"
|
||||
[class]{}-[func]{preOrder}
|
||||
|
||||
[class]{}-[func]{inOrder}
|
||||
|
||||
[class]{}-[func]{postOrder}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="binary_tree_dfs.dart"
|
||||
[class]{}-[func]{preOrder}
|
||||
|
||||
[class]{}-[func]{inOrder}
|
||||
|
||||
[class]{}-[func]{postOrder}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="binary_tree_dfs.rs"
|
||||
[class]{}-[func]{pre_order}
|
||||
|
||||
[class]{}-[func]{in_order}
|
||||
|
||||
[class]{}-[func]{post_order}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="binary_tree_dfs.c"
|
||||
[class]{}-[func]{preOrder}
|
||||
|
||||
[class]{}-[func]{inOrder}
|
||||
|
||||
[class]{}-[func]{postOrder}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="binary_tree_dfs.zig"
|
||||
[class]{}-[func]{preOrder}
|
||||
|
||||
[class]{}-[func]{inOrder}
|
||||
|
||||
[class]{}-[func]{postOrder}
|
||||
```
|
||||
|
||||
!!! note
|
||||
|
||||
深度优先搜索也可以基于迭代实现,有兴趣的同学可以自行研究。
|
||||
|
||||
下图展示了前序遍历二叉树的递归过程,其可分为“递”和“归”两个逆向的部分。
|
||||
|
||||
1. “递”表示开启新方法,程序在此过程中访问下一个节点。
|
||||
2. “归”表示函数返回,代表当前节点已经访问完毕。
|
||||
|
||||
=== "<1>"
|
||||

|
||||
|
||||
=== "<2>"
|
||||

|
||||
|
||||
=== "<3>"
|
||||

|
||||
|
||||
=== "<4>"
|
||||

|
||||
|
||||
=== "<5>"
|
||||

|
||||
|
||||
=== "<6>"
|
||||

|
||||
|
||||
=== "<7>"
|
||||

|
||||
|
||||
=== "<8>"
|
||||

|
||||
|
||||
=== "<9>"
|
||||

|
||||
|
||||
=== "<10>"
|
||||

|
||||
|
||||
=== "<11>"
|
||||

|
||||
|
||||
### 复杂度分析
|
||||
|
||||
- **时间复杂度 $O(n)$** :所有节点被访问一次,使用 $O(n)$ 时间。
|
||||
- **空间复杂度 $O(n)$** :在最差情况下,即树退化为链表时,递归深度达到 $n$ ,系统占用 $O(n)$ 栈帧空间。
|
@ -1,13 +0,0 @@
|
||||
# 树
|
||||
|
||||
<div class="center-table" markdown>
|
||||
|
||||
{ width="600" }
|
||||
|
||||
</div>
|
||||
|
||||
!!! abstract
|
||||
|
||||
参天大树充满生命力,其根深叶茂,分枝扶疏。
|
||||
|
||||
它为我们展现了数据分治的生动形态。
|
@ -1,54 +0,0 @@
|
||||
# 小结
|
||||
|
||||
### 重点回顾
|
||||
|
||||
- 二叉树是一种非线性数据结构,体现“一分为二”的分治逻辑。每个二叉树节点包含一个值以及两个指针,分别指向其左子节点和右子节点。
|
||||
- 对于二叉树中的某个节点,其左(右)子节点及其以下形成的树被称为该节点的左(右)子树。
|
||||
- 二叉树的相关术语包括根节点、叶节点、层、度、边、高度和深度等。
|
||||
- 二叉树的初始化、节点插入和节点删除操作与链表操作方法类似。
|
||||
- 常见的二叉树类型有完美二叉树、完全二叉树、满二叉树和平衡二叉树。完美二叉树是最理想的状态,而链表是退化后的最差状态。
|
||||
- 二叉树可以用数组表示,方法是将节点值和空位按层序遍历顺序排列,并根据父节点与子节点之间的索引映射关系来实现指针。
|
||||
- 二叉树的层序遍历是一种广度优先搜索方法,它体现了“一圈一圈向外”的分层遍历方式,通常通过队列来实现。
|
||||
- 前序、中序、后序遍历皆属于深度优先搜索,它们体现了“走到尽头,再回头继续”的回溯遍历方式,通常使用递归来实现。
|
||||
- 二叉搜索树是一种高效的元素查找数据结构,其查找、插入和删除操作的时间复杂度均为 $O(\log n)$ 。当二叉搜索树退化为链表时,各项时间复杂度会劣化至 $O(n)$ 。
|
||||
- AVL 树,也称为平衡二叉搜索树,它通过旋转操作,确保在不断插入和删除节点后,树仍然保持平衡。
|
||||
- AVL 树的旋转操作包括右旋、左旋、先右旋再左旋、先左旋再右旋。在插入或删除节点后,AVL 树会从底向顶执行旋转操作,使树重新恢复平衡。
|
||||
|
||||
### Q & A
|
||||
|
||||
!!! question "对于只有一个节点的二叉树,树的高度和根节点的深度都是 $0$ 吗?"
|
||||
|
||||
是的,因为高度和深度通常定义为“走过边的数量”。
|
||||
|
||||
!!! question "二叉树中的插入与删除一般都是由一套操作配合完成的,这里的“一套操作”指什么呢?可以理解为资源的子节点的资源释放吗?"
|
||||
|
||||
拿二叉搜索树来举例,删除节点操作要分为三种情况处理,其中每种情况都需要进行多个步骤的节点操作。
|
||||
|
||||
!!! question "为什么 DFS 遍历二叉树有前、中、后三种顺序,分别有什么用呢?"
|
||||
|
||||
DFS 的前、中、后序遍历和访问数组的顺序类似,是遍历二叉树的基本方法,利用这三种遍历方法,我们可以得到一个特定顺序的遍历结果。例如在二叉搜索树中,由于结点大小满足 `左子结点值 < 根结点值 < 右子结点值` ,因此我们只要按照 `左->根->右` 的优先级遍历树,就可以获得有序的节点序列。
|
||||
|
||||
!!! question "右旋操作是处理失衡节点 `node`、`child`、`grand_child` 之间的关系,那 `node` 的父节点和 `node` 原来的连接不需要维护吗?右旋操作后岂不是断掉了?"
|
||||
|
||||
我们需要从递归的视角来看这个问题。右旋操作 `right_rotate(root)` 传入的是子树的根节点,最终 `return child` 返回旋转之后的子树的根节点。子树的根节点和其父节点的连接是在该函数返回后完成的,不属于右旋操作的维护范围。
|
||||
|
||||
!!! question "在 C++ 中,函数被划分到 `private` 和 `public` 中,这方面有什么考量吗?为什么要将 `height()` 函数和 `updateHeight()` 函数分别放在 `public` 和 `private` 中呢?"
|
||||
|
||||
主要看方法的使用范围,如果方法只在类内部使用,那么就设计为 `private` 。例如,用户单独调用 `updateHeight()` 是没有意义的,它只是插入、删除操作中的一步。而 `height()` 是访问结点高度,类似于 `vector.size()` ,因此设置成 `public` 以便使用。
|
||||
|
||||
!!! question "请问如何从一组输入数据构建一个二叉搜索树?根节点的选择是不是很重要?"
|
||||
|
||||
是的,构建树的方法已在二叉搜索树代码中的 `build_tree()` 方法中给出。至于根节点的选择,我们通常会将输入数据排序,然后用中点元素作为根节点,再递归地构建左右子树。这样做可以最大程度保证树的平衡性。
|
||||
|
||||
!!! question "在 Java 中,字符串对比是否一定要用 `equals()` 方法?"
|
||||
|
||||
在 Java 中,对于基本数据类型,`==` 用于对比两个变量的值是否相等。对于引用类型,两种符号的工作原理是不同的。
|
||||
|
||||
- `==` :用来比较两个变量是否指向同一个对象,即它们在内存中的位置是否相同。
|
||||
- `equals()`:用来对比两个对象的值是否相等。
|
||||
|
||||
因此如果要对比值,我们通常会用 `equals()` 。然而,通过 `String a = "hi"; String b = "hi";` 初始化的字符串都存储在字符串常量池中,它们指向同一个对象,因此也可以用 `a == b` 来比较两个字符串的内容。
|
||||
|
||||
!!! question "广度优先遍历到最底层之前,队列中的节点数量是 $2^h$ 吗?"
|
||||
|
||||
是的,例如高度 $h = 2$ 的满二叉树,其节点总数 $n = 7$ ,则底层节点数量 $4 = 2^h = (n + 1) / 2$ 。
|