Add Swift language blocks to the docs.

This commit is contained in:
Yudong Jin
2023-01-08 19:41:05 +08:00
parent 3ba37dba3a
commit 73e3452838
22 changed files with 414 additions and 70 deletions
+48
View File
@@ -94,6 +94,12 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit
}
```
=== "Swift"
```swift title="avl_tree.swift"
```
「结点高度」是最远叶结点到该结点的距离,即走过的「边」的数量。需要特别注意,**叶结点的高度为 0 ,空结点的高度为 -1** 。我们封装两个工具函数,分别用于获取与更新结点的高度。
=== "Java"
@@ -176,6 +182,12 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit
}
```
=== "Swift"
```swift title="avl_tree.swift"
```
### 结点平衡因子
结点的「平衡因子 Balance Factor」是 **结点的左子树高度减去右子树高度**,并定义空结点的平衡因子为 0 。同样地,我们将获取结点平衡因子封装成函数,以便后续使用。
@@ -247,6 +259,12 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit
}
```
=== "Swift"
```swift title="avl_tree.swift"
```
!!! note
设平衡因子为 $f$ ,则一棵 AVL 树的任意结点的平衡因子皆满足 $-1 \le f \le 1$ 。
@@ -361,6 +379,12 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影
```
=== "Swift"
```swift title="avl_tree.swift"
```
### Case 2 - 左旋
类似地,如果将取上述失衡二叉树的“镜像”,那么则需要「左旋」操作。
@@ -457,6 +481,12 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影
}
```
=== "Swift"
```swift title="avl_tree.swift"
```
### Case 3 - 先左后右
对于下图的失衡结点 3 ,**单一使用左旋或右旋都无法使子树恢复平衡**,此时需要「先左旋后右旋」,即先对 `child` 执行「左旋」,再对 `node` 执行「右旋」。
@@ -626,6 +656,12 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影
}
```
=== "Swift"
```swift title="avl_tree.swift"
```
## AVL 树常用操作
### 插入结点
@@ -744,6 +780,12 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影
}
```
=== "Swift"
```swift title="avl_tree.swift"
```
### 删除结点
「AVL 树」删除结点操作与「二叉搜索树」删除结点操作总体相同。类似地,**在删除结点后,也需要从底至顶地执行旋转操作,使所有失衡结点恢复平衡**。
@@ -902,6 +944,12 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影
}
```
=== "Swift"
```swift title="avl_tree.swift"
```
### 查找结点
「AVL 树」的结点查找操作与「二叉搜索树」一致,在此不再赘述。