This commit is contained in:
krahets
2023-11-27 02:32:06 +08:00
parent 32d5bd97aa
commit a4a23e2488
31 changed files with 179 additions and 213 deletions

View File

@ -39,7 +39,7 @@ comments: true
### 7.   C# 环境 ### 7.   C# 环境
1. 下载并安装 [.Net 6.0](https://dotnet.microsoft.com/en-us/download) 。 1. 下载并安装 [.Net 8.0](https://dotnet.microsoft.com/en-us/download) 。
2. 在 VSCode 的插件市场中搜索 `C# Dev Kit` ,安装 C# Dev Kit [配置教程](https://code.visualstudio.com/docs/csharp/get-started))。 2. 在 VSCode 的插件市场中搜索 `C# Dev Kit` ,安装 C# Dev Kit [配置教程](https://code.visualstudio.com/docs/csharp/get-started))。
3. 也可使用 Visual Studio[安装教程](https://learn.microsoft.com/zh-cn/visualstudio/install/install-visual-studio?view=vs-2022))。 3. 也可使用 Visual Studio[安装教程](https://learn.microsoft.com/zh-cn/visualstudio/install/install-visual-studio?view=vs-2022))。

View File

@ -49,7 +49,7 @@ comments: true
```csharp title="array.cs" ```csharp title="array.cs"
/* 初始化数组 */ /* 初始化数组 */
int[] arr = new int[5]; // { 0, 0, 0, 0, 0 } int[] arr = new int[5]; // { 0, 0, 0, 0, 0 }
int[] nums = { 1, 3, 2, 5, 4 }; int[] nums = [1, 3, 2, 5, 4];
``` ```
=== "Go" === "Go"

View File

@ -58,10 +58,9 @@ comments: true
```csharp title="" ```csharp title=""
/* 链表节点类 */ /* 链表节点类 */
class ListNode { class ListNode(int x) { //构造函数
int val; // 节点值 int val = x; // 节点值
ListNode next; // 指向下一节点的引用 ListNode? next; // 指向下一节点的引用
ListNode(int x) => val = x; //构造函数
} }
``` ```
@ -774,7 +773,7 @@ comments: true
```csharp title="linked_list.cs" ```csharp title="linked_list.cs"
/* 访问链表中索引为 index 的节点 */ /* 访问链表中索引为 index 的节点 */
ListNode? Access(ListNode head, int index) { ListNode? Access(ListNode? head, int index) {
for (int i = 0; i < index; i++) { for (int i = 0; i < index; i++) {
if (head == null) if (head == null)
return null; return null;
@ -953,7 +952,7 @@ comments: true
```csharp title="linked_list.cs" ```csharp title="linked_list.cs"
/* 在链表中查找值为 target 的首个节点 */ /* 在链表中查找值为 target 的首个节点 */
int Find(ListNode head, int target) { int Find(ListNode? head, int target) {
int index = 0; int index = 0;
while (head != null) { while (head != null) {
if (head.val == target) if (head.val == target)
@ -1162,11 +1161,10 @@ comments: true
```csharp title="" ```csharp title=""
/* 双向链表节点类 */ /* 双向链表节点类 */
class ListNode { class ListNode(int x) { // 构造函数
int val; // 节点值 int val = x; // 节点值
ListNode next; // 指向后继节点的引用 ListNode next; // 指向后继节点的引用
ListNode prev; // 指向前驱节点的引用 ListNode prev; // 指向前驱节点的引用
ListNode(int x) => val = x; // 构造函数
} }
``` ```

View File

@ -58,10 +58,10 @@ comments: true
```csharp title="list.cs" ```csharp title="list.cs"
/* 初始化列表 */ /* 初始化列表 */
// 无初始值 // 无初始值
List<int> nums1 = new(); List<int> nums1 = [];
// 有初始值 // 有初始值
int[] numbers = new int[] { 1, 3, 2, 5, 4 }; int[] numbers = [1, 3, 2, 5, 4];
List<int> nums = numbers.ToList(); List<int> nums = [.. numbers];
``` ```
=== "Go" === "Go"
@ -704,7 +704,7 @@ comments: true
```csharp title="list.cs" ```csharp title="list.cs"
/* 拼接两个列表 */ /* 拼接两个列表 */
List<int> nums1 = new() { 6, 8, 7, 10, 9 }; List<int> nums1 = [6, 8, 7, 10, 9];
nums.AddRange(nums1); // 将列表 nums1 拼接到 nums 之后 nums.AddRange(nums1); // 将列表 nums1 拼接到 nums 之后
``` ```

View File

@ -66,7 +66,7 @@ comments: true
```csharp title="preorder_traversal_i_compact.cs" ```csharp title="preorder_traversal_i_compact.cs"
/* 前序遍历:例题一 */ /* 前序遍历:例题一 */
void PreOrder(TreeNode root) { void PreOrder(TreeNode? root) {
if (root == null) { if (root == null) {
return; return;
} }
@ -288,7 +288,7 @@ comments: true
```csharp title="preorder_traversal_ii_compact.cs" ```csharp title="preorder_traversal_ii_compact.cs"
/* 前序遍历:例题二 */ /* 前序遍历:例题二 */
void PreOrder(TreeNode root) { void PreOrder(TreeNode? root) {
if (root == null) { if (root == null) {
return; return;
} }
@ -588,7 +588,7 @@ comments: true
```csharp title="preorder_traversal_iii_compact.cs" ```csharp title="preorder_traversal_iii_compact.cs"
/* 前序遍历:例题三 */ /* 前序遍历:例题三 */
void PreOrder(TreeNode root) { void PreOrder(TreeNode? root) {
// 剪枝 // 剪枝
if (root == null || root.val == 3) { if (root == null || root.val == 3) {
return; return;
@ -1267,7 +1267,7 @@ comments: true
// 尝试:做出选择,更新状态 // 尝试:做出选择,更新状态
MakeChoice(state, choice); MakeChoice(state, choice);
// 进行下一轮选择 // 进行下一轮选择
Backtrack(state, new List<TreeNode> { choice.left, choice.right }, res); Backtrack(state, [choice.left!, choice.right!], res);
// 回退:撤销选择,恢复到之前的状态 // 回退:撤销选择,恢复到之前的状态
UndoChoice(state, choice); UndoChoice(state, choice);
} }

View File

@ -207,7 +207,7 @@ comments: true
bool[] cols, bool[] diags1, bool[] diags2) { bool[] cols, bool[] diags1, bool[] diags2) {
// 当放置完所有行时,记录解 // 当放置完所有行时,记录解
if (row == n) { if (row == n) {
List<List<string>> copyState = new(); List<List<string>> copyState = [];
foreach (List<string> sRow in state) { foreach (List<string> sRow in state) {
copyState.Add(new List<string>(sRow)); copyState.Add(new List<string>(sRow));
} }
@ -236,9 +236,9 @@ comments: true
/* 求解 N 皇后 */ /* 求解 N 皇后 */
List<List<List<string>>> NQueens(int n) { List<List<List<string>>> NQueens(int n) {
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位 // 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
List<List<string>> state = new(); List<List<string>> state = [];
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
List<string> row = new(); List<string> row = [];
for (int j = 0; j < n; j++) { for (int j = 0; j < n; j++) {
row.Add("#"); row.Add("#");
} }
@ -247,7 +247,7 @@ comments: true
bool[] cols = new bool[n]; // 记录列是否有皇后 bool[] cols = new bool[n]; // 记录列是否有皇后
bool[] diags1 = new bool[2 * n - 1]; // 记录主对角线是否有皇后 bool[] diags1 = new bool[2 * n - 1]; // 记录主对角线是否有皇后
bool[] diags2 = new bool[2 * n - 1]; // 记录副对角线是否有皇后 bool[] diags2 = new bool[2 * n - 1]; // 记录副对角线是否有皇后
List<List<List<string>>> res = new(); List<List<List<string>>> res = [];
Backtrack(0, n, state, res, cols, diags1, diags2); Backtrack(0, n, state, res, cols, diags1, diags2);

View File

@ -187,8 +187,8 @@ comments: true
/* 全排列 I */ /* 全排列 I */
List<List<int>> PermutationsI(int[] nums) { List<List<int>> PermutationsI(int[] nums) {
List<List<int>> res = new(); List<List<int>> res = [];
Backtrack(new List<int>(), nums, new bool[nums.Length], res); Backtrack([], nums, new bool[nums.Length], res);
return res; return res;
} }
``` ```
@ -623,7 +623,7 @@ comments: true
return; return;
} }
// 遍历所有选择 // 遍历所有选择
ISet<int> duplicated = new HashSet<int>(); HashSet<int> duplicated = [];
for (int i = 0; i < choices.Length; i++) { for (int i = 0; i < choices.Length; i++) {
int choice = choices[i]; int choice = choices[i];
// 剪枝:不允许重复选择元素 且 不允许重复选择相等元素 // 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
@ -643,8 +643,8 @@ comments: true
/* 全排列 II */ /* 全排列 II */
List<List<int>> PermutationsII(int[] nums) { List<List<int>> PermutationsII(int[] nums) {
List<List<int>> res = new(); List<List<int>> res = [];
Backtrack(new List<int>(), nums, new bool[nums.Length], res); Backtrack([], nums, new bool[nums.Length], res);
return res; return res;
} }
``` ```

View File

@ -154,9 +154,9 @@ comments: true
/* 求解子集和 I包含重复子集 */ /* 求解子集和 I包含重复子集 */
List<List<int>> SubsetSumINaive(int[] nums, int target) { List<List<int>> SubsetSumINaive(int[] nums, int target) {
List<int> state = new(); // 状态(子集) List<int> state = []; // 状态(子集)
int total = 0; // 子集和 int total = 0; // 子集和
List<List<int>> res = new(); // 结果列表(子集列表) List<List<int>> res = []; // 结果列表(子集列表)
Backtrack(state, target, total, nums, res); Backtrack(state, target, total, nums, res);
return res; return res;
} }
@ -609,10 +609,10 @@ comments: true
/* 求解子集和 I */ /* 求解子集和 I */
List<List<int>> SubsetSumI(int[] nums, int target) { List<List<int>> SubsetSumI(int[] nums, int target) {
List<int> state = new(); // 状态(子集) List<int> state = []; // 状态(子集)
Array.Sort(nums); // 对 nums 进行排序 Array.Sort(nums); // 对 nums 进行排序
int start = 0; // 遍历起始点 int start = 0; // 遍历起始点
List<List<int>> res = new(); // 结果列表(子集列表) List<List<int>> res = []; // 结果列表(子集列表)
Backtrack(state, target, nums, start, res); Backtrack(state, target, nums, start, res);
return res; return res;
} }
@ -1093,10 +1093,10 @@ comments: true
/* 求解子集和 II */ /* 求解子集和 II */
List<List<int>> SubsetSumII(int[] nums, int target) { List<List<int>> SubsetSumII(int[] nums, int target) {
List<int> state = new(); // 状态(子集) List<int> state = []; // 状态(子集)
Array.Sort(nums); // 对 nums 进行排序 Array.Sort(nums); // 对 nums 进行排序
int start = 0; // 遍历起始点 int start = 0; // 遍历起始点
List<List<int>> res = new(); // 结果列表(子集列表) List<List<int>> res = []; // 结果列表(子集列表)
Backtrack(state, target, nums, start, res); Backtrack(state, target, nums, start, res);
return res; return res;
} }

View File

@ -104,10 +104,9 @@ comments: true
```csharp title="" ```csharp title=""
/* 类 */ /* 类 */
class Node { class Node(int x) {
int val; int val = x;
Node next; Node next;
Node(int x) { val = x; }
} }
/* 函数 */ /* 函数 */
@ -119,7 +118,7 @@ comments: true
int Algorithm(int n) { // 输入数据 int Algorithm(int n) { // 输入数据
const int a = 0; // 暂存数据(常量) const int a = 0; // 暂存数据(常量)
int b = 0; // 暂存数据(变量) int b = 0; // 暂存数据(变量)
Node node = new(0); // 暂存数据(对象) Node node = new(0); // 暂存数据(对象)
int c = Function(); // 栈帧空间(调用函数) int c = Function(); // 栈帧空间(调用函数)
return a + b + c; // 输出数据 return a + b + c; // 输出数据
} }
@ -1123,12 +1122,12 @@ $$
// 长度为 n 的数组占用 O(n) 空间 // 长度为 n 的数组占用 O(n) 空间
int[] nums = new int[n]; int[] nums = new int[n];
// 长度为 n 的列表占用 O(n) 空间 // 长度为 n 的列表占用 O(n) 空间
List<ListNode> nodes = new(); List<ListNode> nodes = [];
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
nodes.Add(new ListNode(i)); nodes.Add(new ListNode(i));
} }
// 长度为 n 的哈希表占用 O(n) 空间 // 长度为 n 的哈希表占用 O(n) 空间
Dictionary<int, string> map = new(); Dictionary<int, string> map = [];
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
map.Add(i, i.ToString()); map.Add(i, i.ToString());
} }
@ -1524,9 +1523,9 @@ $$
// 矩阵占用 O(n^2) 空间 // 矩阵占用 O(n^2) 空间
int[,] numMatrix = new int[n, n]; int[,] numMatrix = new int[n, n];
// 二维列表占用 O(n^2) 空间 // 二维列表占用 O(n^2) 空间
List<List<int>> numList = new(); List<List<int>> numList = [];
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
List<int> tmp = new(); List<int> tmp = [];
for (int j = 0; j < n; j++) { for (int j = 0; j < n; j++) {
tmp.Add(0); tmp.Add(0);
} }

View File

@ -2338,7 +2338,7 @@ $$
int Logarithmic(float n) { int Logarithmic(float n) {
int count = 0; int count = 0;
while (n > 1) { while (n > 1) {
n = n / 2; n /= 2;
count++; count++;
} }
return count; return count;

View File

@ -172,7 +172,7 @@ comments: true
```csharp title="build_tree.cs" ```csharp title="build_tree.cs"
/* 构建二叉树:分治 */ /* 构建二叉树:分治 */
TreeNode DFS(int[] preorder, Dictionary<int, int> inorderMap, int i, int l, int r) { TreeNode? DFS(int[] preorder, Dictionary<int, int> inorderMap, int i, int l, int r) {
// 子树区间为空时终止 // 子树区间为空时终止
if (r - l < 0) if (r - l < 0)
return null; return null;
@ -189,13 +189,13 @@ comments: true
} }
/* 构建二叉树 */ /* 构建二叉树 */
TreeNode BuildTree(int[] preorder, int[] inorder) { TreeNode? BuildTree(int[] preorder, int[] inorder) {
// 初始化哈希表,存储 inorder 元素到索引的映射 // 初始化哈希表,存储 inorder 元素到索引的映射
Dictionary<int, int> inorderMap = new(); Dictionary<int, int> inorderMap = [];
for (int i = 0; i < inorder.Length; i++) { for (int i = 0; i < inorder.Length; i++) {
inorderMap.TryAdd(inorder[i], i); inorderMap.TryAdd(inorder[i], i);
} }
TreeNode root = DFS(preorder, inorderMap, 0, 0, inorder.Length - 1); TreeNode? root = DFS(preorder, inorderMap, 0, 0, inorder.Length - 1);
return root; return root;
} }
``` ```

View File

@ -126,9 +126,9 @@ comments: true
/* 爬楼梯:回溯 */ /* 爬楼梯:回溯 */
int ClimbingStairsBacktrack(int n) { int ClimbingStairsBacktrack(int n) {
List<int> choices = new() { 1, 2 }; // 可选择向上爬 1 或 2 阶 List<int> choices = [1, 2]; // 可选择向上爬 1 或 2 阶
int state = 0; // 从第 0 阶开始爬 int state = 0; // 从第 0 阶开始爬
List<int> res = new() { 0 }; // 使用 res[0] 记录方案数量 List<int> res = [0]; // 使用 res[0] 记录方案数量
Backtrack(choices, state, n, res); Backtrack(choices, state, n, res);
return res[0]; return res[0];
} }

View File

@ -291,13 +291,13 @@ comments: true
```csharp title="graph_adjacency_matrix.cs" ```csharp title="graph_adjacency_matrix.cs"
/* 基于邻接矩阵实现的无向图类 */ /* 基于邻接矩阵实现的无向图类 */
class GraphAdjMat { class GraphAdjMat {
readonly List<int> vertices; // 顶点列表,元素代表“顶点值”,索引代表“顶点索引” List<int> vertices; // 顶点列表,元素代表“顶点值”,索引代表“顶点索引”
readonly List<List<int>> adjMat; // 邻接矩阵,行列索引对应“顶点索引” List<List<int>> adjMat; // 邻接矩阵,行列索引对应“顶点索引”
/* 构造函数 */ /* 构造函数 */
public GraphAdjMat(int[] vertices, int[][] edges) { public GraphAdjMat(int[] vertices, int[][] edges) {
this.vertices = new List<int>(); this.vertices = [];
this.adjMat = new List<List<int>>(); this.adjMat = [];
// 添加顶点 // 添加顶点
foreach (int val in vertices) { foreach (int val in vertices) {
AddVertex(val); AddVertex(val);
@ -310,7 +310,7 @@ comments: true
} }
/* 获取顶点数量 */ /* 获取顶点数量 */
public int Size() { int Size() {
return vertices.Count; return vertices.Count;
} }
@ -1311,7 +1311,7 @@ comments: true
/* 构造函数 */ /* 构造函数 */
public GraphAdjList(Vertex[][] edges) { public GraphAdjList(Vertex[][] edges) {
this.adjList = new Dictionary<Vertex, List<Vertex>>(); adjList = [];
// 添加所有顶点和边 // 添加所有顶点和边
foreach (Vertex[] edge in edges) { foreach (Vertex[] edge in edges) {
AddVertex(edge[0]); AddVertex(edge[0]);
@ -1321,7 +1321,7 @@ comments: true
} }
/* 获取顶点数量 */ /* 获取顶点数量 */
public int Size() { int Size() {
return adjList.Count; return adjList.Count;
} }
@ -1348,7 +1348,7 @@ comments: true
if (adjList.ContainsKey(vet)) if (adjList.ContainsKey(vet))
return; return;
// 在邻接表中添加一个新链表 // 在邻接表中添加一个新链表
adjList.Add(vet, new List<Vertex>()); adjList.Add(vet, []);
} }
/* 删除顶点 */ /* 删除顶点 */
@ -1367,7 +1367,7 @@ comments: true
public void Print() { public void Print() {
Console.WriteLine("邻接表 ="); Console.WriteLine("邻接表 =");
foreach (KeyValuePair<Vertex, List<Vertex>> pair in adjList) { foreach (KeyValuePair<Vertex, List<Vertex>> pair in adjList) {
List<int> tmp = new(); List<int> tmp = [];
foreach (Vertex vertex in pair.Value) foreach (Vertex vertex in pair.Value)
tmp.Add(vertex.val); tmp.Add(vertex.val);
Console.WriteLine(pair.Key.val + ": [" + string.Join(", ", tmp) + "],"); Console.WriteLine(pair.Key.val + ": [" + string.Join(", ", tmp) + "],");

View File

@ -121,9 +121,9 @@ BFS 通常借助队列来实现。队列具有“先入先出”的性质,这
// 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点 // 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点
List<Vertex> GraphBFS(GraphAdjList graph, Vertex startVet) { List<Vertex> GraphBFS(GraphAdjList graph, Vertex startVet) {
// 顶点遍历序列 // 顶点遍历序列
List<Vertex> res = new(); List<Vertex> res = [];
// 哈希表,用于记录已被访问过的顶点 // 哈希表,用于记录已被访问过的顶点
HashSet<Vertex> visited = new() { startVet }; HashSet<Vertex> visited = [startVet];
// 队列用于实现 BFS // 队列用于实现 BFS
Queue<Vertex> que = new(); Queue<Vertex> que = new();
que.Enqueue(startVet); que.Enqueue(startVet);
@ -579,9 +579,9 @@ BFS 通常借助队列来实现。队列具有“先入先出”的性质,这
// 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点 // 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点
List<Vertex> GraphDFS(GraphAdjList graph, Vertex startVet) { List<Vertex> GraphDFS(GraphAdjList graph, Vertex startVet) {
// 顶点遍历序列 // 顶点遍历序列
List<Vertex> res = new(); List<Vertex> res = [];
// 哈希表,用于记录已被访问过的顶点 // 哈希表,用于记录已被访问过的顶点
HashSet<Vertex> visited = new(); HashSet<Vertex> visited = [];
DFS(graph, visited, res, startVet); DFS(graph, visited, res, startVet);
return res; return res;
} }

View File

@ -155,14 +155,9 @@ comments: true
```csharp title="fractional_knapsack.cs" ```csharp title="fractional_knapsack.cs"
/* 物品 */ /* 物品 */
class Item { class Item(int w, int v) {
public int w; // 物品重量 public int w = w; // 物品重量
public int v; // 物品价值 public int v = v; // 物品价值
public Item(int w, int v) {
this.w = w;
this.v = v;
}
} }
/* 分数背包:贪心 */ /* 分数背包:贪心 */

View File

@ -731,7 +731,7 @@ $$
int hashStr = str.GetHashCode(); int hashStr = str.GetHashCode();
// 字符串 Hello 算法 的哈希值为 -586107568; // 字符串 Hello 算法 的哈希值为 -586107568;
object[] arr = { 12836, "小哈" }; object[] arr = [12836, "小哈"];
int hashTup = arr.GetHashCode(); int hashTup = arr.GetHashCode();
// 数组 [12836, 小哈] 的哈希值为 42931033; // 数组 [12836, 小哈] 的哈希值为 42931033;

View File

@ -359,8 +359,8 @@ comments: true
class HashMapChaining { class HashMapChaining {
int size; // 键值对数量 int size; // 键值对数量
int capacity; // 哈希表容量 int capacity; // 哈希表容量
readonly double loadThres; // 触发扩容的负载因子阈值 double loadThres; // 触发扩容的负载因子阈值
readonly int extendRatio; // 扩容倍数 int extendRatio; // 扩容倍数
List<List<Pair>> buckets; // 桶数组 List<List<Pair>> buckets; // 桶数组
/* 构造方法 */ /* 构造方法 */
@ -371,17 +371,17 @@ comments: true
extendRatio = 2; extendRatio = 2;
buckets = new List<List<Pair>>(capacity); buckets = new List<List<Pair>>(capacity);
for (int i = 0; i < capacity; i++) { for (int i = 0; i < capacity; i++) {
buckets.Add(new List<Pair>()); buckets.Add([]);
} }
} }
/* 哈希函数 */ /* 哈希函数 */
private int HashFunc(int key) { int HashFunc(int key) {
return key % capacity; return key % capacity;
} }
/* 负载因子 */ /* 负载因子 */
private double LoadFactor() { double LoadFactor() {
return (double)size / capacity; return (double)size / capacity;
} }
@ -431,14 +431,14 @@ comments: true
} }
/* 扩容哈希表 */ /* 扩容哈希表 */
private void Extend() { void Extend() {
// 暂存原哈希表 // 暂存原哈希表
List<List<Pair>> bucketsTmp = buckets; List<List<Pair>> bucketsTmp = buckets;
// 初始化扩容后的新哈希表 // 初始化扩容后的新哈希表
capacity *= extendRatio; capacity *= extendRatio;
buckets = new List<List<Pair>>(capacity); buckets = new List<List<Pair>>(capacity);
for (int i = 0; i < capacity; i++) { for (int i = 0; i < capacity; i++) {
buckets.Add(new List<Pair>()); buckets.Add([]);
} }
size = 0; size = 0;
// 将键值对从原哈希表搬运至新哈希表 // 将键值对从原哈希表搬运至新哈希表
@ -452,7 +452,7 @@ comments: true
/* 打印哈希表 */ /* 打印哈希表 */
public void Print() { public void Print() {
foreach (List<Pair> bucket in buckets) { foreach (List<Pair> bucket in buckets) {
List<string> res = new(); List<string> res = [];
foreach (Pair pair in bucket) { foreach (Pair pair in bucket) {
res.Add(pair.key + " -> " + pair.val); res.Add(pair.key + " -> " + pair.val);
} }
@ -1727,12 +1727,12 @@ comments: true
```csharp title="hash_map_open_addressing.cs" ```csharp title="hash_map_open_addressing.cs"
/* 开放寻址哈希表 */ /* 开放寻址哈希表 */
class HashMapOpenAddressing { class HashMapOpenAddressing {
private int size; // 键值对数量 int size; // 键值对数量
private int capacity = 4; // 哈希表容量 int capacity = 4; // 哈希表容量
private readonly double loadThres = 2.0 / 3.0; // 触发扩容的负载因子阈值 double loadThres = 2.0 / 3.0; // 触发扩容的负载因子阈值
private readonly int extendRatio = 2; // 扩容倍数 int extendRatio = 2; // 扩容倍数
private Pair[] buckets; // 桶数组 Pair[] buckets; // 桶数组
private readonly Pair TOMBSTONE = new(-1, "-1"); // 删除标记 Pair TOMBSTONE = new(-1, "-1"); // 删除标记
/* 构造方法 */ /* 构造方法 */
public HashMapOpenAddressing() { public HashMapOpenAddressing() {
@ -1741,17 +1741,17 @@ comments: true
} }
/* 哈希函数 */ /* 哈希函数 */
private int HashFunc(int key) { int HashFunc(int key) {
return key % capacity; return key % capacity;
} }
/* 负载因子 */ /* 负载因子 */
private double LoadFactor() { double LoadFactor() {
return (double)size / capacity; return (double)size / capacity;
} }
/* 搜索 key 对应的桶索引 */ /* 搜索 key 对应的桶索引 */
private int FindBucket(int key) { int FindBucket(int key) {
int index = HashFunc(key); int index = HashFunc(key);
int firstTombstone = -1; int firstTombstone = -1;
// 线性探测,当遇到空桶时跳出 // 线性探测,当遇到空桶时跳出
@ -1819,7 +1819,7 @@ comments: true
} }
/* 扩容哈希表 */ /* 扩容哈希表 */
private void Extend() { void Extend() {
// 暂存原哈希表 // 暂存原哈希表
Pair[] bucketsTmp = buckets; Pair[] bucketsTmp = buckets;
// 初始化扩容后的新哈希表 // 初始化扩容后的新哈希表

View File

@ -776,28 +776,24 @@ index = hash(key) % capacity
```csharp title="array_hash_map.cs" ```csharp title="array_hash_map.cs"
/* 键值对 int->string */ /* 键值对 int->string */
class Pair { class Pair(int key, string val) {
public int key; public int key = key;
public string val; public string val = val;
public Pair(int key, string val) {
this.key = key;
this.val = val;
}
} }
/* 基于数组简易实现的哈希表 */ /* 基于数组简易实现的哈希表 */
class ArrayHashMap { class ArrayHashMap {
private readonly List<Pair?> buckets; List<Pair?> buckets;
public ArrayHashMap() { public ArrayHashMap() {
// 初始化数组,包含 100 个桶 // 初始化数组,包含 100 个桶
buckets = new(); buckets = [];
for (int i = 0; i < 100; i++) { for (int i = 0; i < 100; i++) {
buckets.Add(null); buckets.Add(null);
} }
} }
/* 哈希函数 */ /* 哈希函数 */
private int HashFunc(int key) { int HashFunc(int key) {
int index = key % 100; int index = key % 100;
return index; return index;
} }
@ -826,7 +822,7 @@ index = hash(key) % capacity
/* 获取所有键值对 */ /* 获取所有键值对 */
public List<Pair> PairSet() { public List<Pair> PairSet() {
List<Pair> pairSet = new(); List<Pair> pairSet = [];
foreach (Pair? pair in buckets) { foreach (Pair? pair in buckets) {
if (pair != null) if (pair != null)
pairSet.Add(pair); pairSet.Add(pair);
@ -836,7 +832,7 @@ index = hash(key) % capacity
/* 获取所有键 */ /* 获取所有键 */
public List<int> KeySet() { public List<int> KeySet() {
List<int> keySet = new(); List<int> keySet = [];
foreach (Pair? pair in buckets) { foreach (Pair? pair in buckets) {
if (pair != null) if (pair != null)
keySet.Add(pair.key); keySet.Add(pair.key);
@ -846,7 +842,7 @@ index = hash(key) % capacity
/* 获取所有值 */ /* 获取所有值 */
public List<string> ValueSet() { public List<string> ValueSet() {
List<string> valueSet = new(); List<string> valueSet = [];
foreach (Pair? pair in buckets) { foreach (Pair? pair in buckets) {
if (pair != null) if (pair != null)
valueSet.Add(pair.val); valueSet.Add(pair.val);
@ -1462,7 +1458,7 @@ index = hash(key) % capacity
for (i = 0; i < HASHTABLE_CAPACITY; i++) { for (i = 0; i < HASHTABLE_CAPACITY; i++) {
if (hmap->buckets[i] != NULL) { if (hmap->buckets[i] != NULL) {
entries[index].key = hmap->buckets[i]->key; entries[index].key = hmap->buckets[i]->key;
entries[index].val = malloc(strlen(hmap->buckets[i]->val + 1)); entries[index].val = malloc(strlen(hmap->buckets[i]->val) + 1);
strcpy(entries[index].val, hmap->buckets[i]->val); strcpy(entries[index].val, hmap->buckets[i]->val);
index++; index++;
} }

View File

@ -197,7 +197,7 @@ comments: true
bool isEmpty = maxHeap.Count == 0; bool isEmpty = maxHeap.Count == 0;
/* 输入列表并建堆 */ /* 输入列表并建堆 */
minHeap = new PriorityQueue<int, int>(new List<(int, int)> { (1, 1), (3, 3), (2, 2), (5, 5), (4, 4), }); minHeap = new PriorityQueue<int, int>([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]);
``` ```
=== "Go" === "Go"

View File

@ -75,10 +75,10 @@ comments: true
for (int i = 0; i < size - 1; i++) { for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j < size; j++) { for (int j = i + 1; j < size; j++) {
if (nums[i] + nums[j] == target) if (nums[i] + nums[j] == target)
return new int[] { i, j }; return [i, j];
} }
} }
return Array.Empty<int>(); return [];
} }
``` ```
@ -309,15 +309,15 @@ comments: true
int[] TwoSumHashTable(int[] nums, int target) { int[] TwoSumHashTable(int[] nums, int target) {
int size = nums.Length; int size = nums.Length;
// 辅助哈希表,空间复杂度 O(n) // 辅助哈希表,空间复杂度 O(n)
Dictionary<int, int> dic = new(); Dictionary<int, int> dic = [];
// 单层循环,时间复杂度 O(n) // 单层循环,时间复杂度 O(n)
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
if (dic.ContainsKey(target - nums[i])) { if (dic.ContainsKey(target - nums[i])) {
return new int[] { dic[target - nums[i]], i }; return [dic[target - nums[i]], i];
} }
dic.Add(nums[i], i); dic.Add(nums[i], i);
} }
return Array.Empty<int>(); return [];
} }
``` ```

View File

@ -116,9 +116,9 @@ comments: true
void BucketSort(float[] nums) { void BucketSort(float[] nums) {
// 初始化 k = n/2 个桶,预期向每个桶分配 2 个元素 // 初始化 k = n/2 个桶,预期向每个桶分配 2 个元素
int k = nums.Length / 2; int k = nums.Length / 2;
List<List<float>> buckets = new(); List<List<float>> buckets = [];
for (int i = 0; i < k; i++) { for (int i = 0; i < k; i++) {
buckets.Add(new List<float>()); buckets.Add([]);
} }
// 1. 将数组元素分配到各个桶中 // 1. 将数组元素分配到各个桶中
foreach (float num in nums) { foreach (float num in nums) {

View File

@ -297,7 +297,7 @@ comments: true
} }
// 2. 统计各数字的出现次数 // 2. 统计各数字的出现次数
// counter[num] 代表 num 的出现次数 // counter[num] 代表 num 的出现次数
int *counter = malloc(sizeof(int) * m); int *counter = calloc(m, sizeof(int));
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
counter[nums[i]]++; counter[nums[i]]++;
} }
@ -308,6 +308,8 @@ comments: true
nums[i] = num; nums[i] = num;
} }
} }
// 4. 释放内存
free(counter);
} }
``` ```
@ -744,7 +746,7 @@ $$
} }
// 2. 统计各数字的出现次数 // 2. 统计各数字的出现次数
// counter[num] 代表 num 的出现次数 // counter[num] 代表 num 的出现次数
int *counter = malloc(sizeof(int) * m); int *counter = calloc(m, sizeof(int));
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
counter[nums[i]]++; counter[nums[i]]++;
} }
@ -763,6 +765,8 @@ $$
} }
// 使用结果数组 res 覆盖原数组 nums // 使用结果数组 res 覆盖原数组 nums
memcpy(nums, res, size * sizeof(int)); memcpy(nums, res, size * sizeof(int));
// 5. 释放内存
free(counter);
} }
``` ```

View File

@ -985,20 +985,7 @@ comments: true
return right; return right;
} }
/* 快速排序类(中位基准数优化 */ /* 哨兵划分(三数取中值 */
// 选取三个元素的中位数
int medianThree(int nums[], int left, int mid, int right) {
// 此处使用异或运算来简化代码
// 异或规则为 0 ^ 0 = 1 ^ 1 = 0, 0 ^ 1 = 1 ^ 0 = 1
if ((nums[left] < nums[mid]) ^ (nums[left] < nums[right]))
return left;
else if ((nums[mid] < nums[left]) ^ (nums[mid] < nums[right]))
return mid;
else
return right;
}
// 哨兵划分(三数取中值)
int partitionMedian(int nums[], int left, int right) { int partitionMedian(int nums[], int left, int right) {
// 选取三个候选元素的中位数 // 选取三个候选元素的中位数
int med = medianThree(nums, left, (left + right) / 2, right); int med = medianThree(nums, left, (left + right) / 2, right);

View File

@ -777,22 +777,16 @@ comments: true
```csharp title="linkedlist_deque.cs" ```csharp title="linkedlist_deque.cs"
/* 双向链表节点 */ /* 双向链表节点 */
class ListNode { class ListNode(int val) {
public int val; // 节点值 public int val = val; // 节点值
public ListNode? next; // 后继节点引用 public ListNode? next = null; // 后继节点引用
public ListNode? prev; // 前驱节点引用 public ListNode? prev = null; // 前驱节点引用
public ListNode(int val) {
this.val = val;
prev = null;
next = null;
}
} }
/* 基于双向链表实现的双向队列 */ /* 基于双向链表实现的双向队列 */
class LinkedListDeque { class LinkedListDeque {
private ListNode? front, rear; // 头节点 front, 尾节点 rear ListNode? front, rear; // 头节点 front, 尾节点 rear
private int queSize = 0; // 双向队列的长度 int queSize = 0; // 双向队列的长度
public LinkedListDeque() { public LinkedListDeque() {
front = null; front = null;
@ -810,7 +804,7 @@ comments: true
} }
/* 入队操作 */ /* 入队操作 */
private void Push(int num, bool isFront) { void Push(int num, bool isFront) {
ListNode node = new(num); ListNode node = new(num);
// 若链表为空,则令 front, rear 都指向 node // 若链表为空,则令 front, rear 都指向 node
if (IsEmpty()) { if (IsEmpty()) {
@ -820,14 +814,14 @@ comments: true
// 队首入队操作 // 队首入队操作
else if (isFront) { else if (isFront) {
// 将 node 添加至链表头部 // 将 node 添加至链表头部
front.prev = node; front!.prev = node;
node.next = front; node.next = front;
front = node; // 更新头节点 front = node; // 更新头节点
} }
// 队尾入队操作 // 队尾入队操作
else { else {
// 将 node 添加至链表尾部 // 将 node 添加至链表尾部
rear.next = node; rear!.next = node;
node.prev = rear; node.prev = rear;
rear = node; // 更新尾节点 rear = node; // 更新尾节点
} }
@ -846,7 +840,7 @@ comments: true
} }
/* 出队操作 */ /* 出队操作 */
private int? Pop(bool isFront) { int? Pop(bool isFront) {
if (IsEmpty()) if (IsEmpty())
throw new Exception(); throw new Exception();
int? val; int? val;
@ -857,7 +851,7 @@ comments: true
ListNode? fNext = front?.next; ListNode? fNext = front?.next;
if (fNext != null) { if (fNext != null) {
fNext.prev = null; fNext.prev = null;
front.next = null; front!.next = null;
} }
front = fNext; // 更新头节点 front = fNext; // 更新头节点
} }
@ -868,7 +862,7 @@ comments: true
ListNode? rPrev = rear?.prev; ListNode? rPrev = rear?.prev;
if (rPrev != null) { if (rPrev != null) {
rPrev.next = null; rPrev.next = null;
rear.prev = null; rear!.prev = null;
} }
rear = rPrev; // 更新尾节点 rear = rPrev; // 更新尾节点
} }
@ -2343,18 +2337,18 @@ comments: true
```csharp title="array_deque.cs" ```csharp title="array_deque.cs"
/* 基于环形数组实现的双向队列 */ /* 基于环形数组实现的双向队列 */
class ArrayDeque { class ArrayDeque {
private readonly int[] nums; // 用于存储双向队列元素的数组 int[] nums; // 用于存储双向队列元素的数组
private int front; // 队首指针,指向队首元素 int front; // 队首指针,指向队首元素
private int queSize; // 双向队列长度 int queSize; // 双向队列长度
/* 构造方法 */ /* 构造方法 */
public ArrayDeque(int capacity) { public ArrayDeque(int capacity) {
this.nums = new int[capacity]; nums = new int[capacity];
front = queSize = 0; front = queSize = 0;
} }
/* 获取双向队列的容量 */ /* 获取双向队列的容量 */
public int Capacity() { int Capacity() {
return nums.Length; return nums.Length;
} }
@ -2369,7 +2363,7 @@ comments: true
} }
/* 计算环形数组索引 */ /* 计算环形数组索引 */
private int Index(int i) { int Index(int i) {
// 通过取余操作实现数组首尾相连 // 通过取余操作实现数组首尾相连
// 当 i 越过数组尾部后,回到头部 // 当 i 越过数组尾部后,回到头部
// 当 i 越过数组头部后,回到尾部 // 当 i 越过数组头部后,回到尾部

View File

@ -547,8 +547,8 @@ comments: true
```csharp title="linkedlist_queue.cs" ```csharp title="linkedlist_queue.cs"
/* 基于链表实现的队列 */ /* 基于链表实现的队列 */
class LinkedListQueue { class LinkedListQueue {
private ListNode? front, rear; // 头节点 front ,尾节点 rear ListNode? front, rear; // 头节点 front ,尾节点 rear
private int queSize = 0; int queSize = 0;
public LinkedListQueue() { public LinkedListQueue() {
front = null; front = null;
@ -594,18 +594,18 @@ comments: true
public int Peek() { public int Peek() {
if (IsEmpty()) if (IsEmpty())
throw new Exception(); throw new Exception();
return front.val; return front!.val;
} }
/* 将链表转化为 Array 并返回 */ /* 将链表转化为 Array 并返回 */
public int[] ToArray() { public int[] ToArray() {
if (front == null) if (front == null)
return Array.Empty<int>(); return [];
ListNode node = front; ListNode? node = front;
int[] res = new int[Size()]; int[] res = new int[Size()];
for (int i = 0; i < res.Length; i++) { for (int i = 0; i < res.Length; i++) {
res[i] = node.val; res[i] = node!.val;
node = node.next; node = node.next;
} }
return res; return res;
@ -1445,9 +1445,9 @@ comments: true
```csharp title="array_queue.cs" ```csharp title="array_queue.cs"
/* 基于环形数组实现的队列 */ /* 基于环形数组实现的队列 */
class ArrayQueue { class ArrayQueue {
private readonly int[] nums; // 用于存储队列元素的数组 int[] nums; // 用于存储队列元素的数组
private int front; // 队首指针,指向队首元素 int front; // 队首指针,指向队首元素
private int queSize; // 队列长度 int queSize; // 队列长度
public ArrayQueue(int capacity) { public ArrayQueue(int capacity) {
nums = new int[capacity]; nums = new int[capacity];
@ -1455,7 +1455,7 @@ comments: true
} }
/* 获取队列的容量 */ /* 获取队列的容量 */
public int Capacity() { int Capacity() {
return nums.Length; return nums.Length;
} }

View File

@ -518,8 +518,8 @@ comments: true
```csharp title="linkedlist_stack.cs" ```csharp title="linkedlist_stack.cs"
/* 基于链表实现的栈 */ /* 基于链表实现的栈 */
class LinkedListStack { class LinkedListStack {
private ListNode? stackPeek; // 将头节点作为栈顶 ListNode? stackPeek; // 将头节点作为栈顶
private int stkSize = 0; // 栈的长度 int stkSize = 0; // 栈的长度
public LinkedListStack() { public LinkedListStack() {
stackPeek = null; stackPeek = null;
@ -547,7 +547,7 @@ comments: true
/* 出栈 */ /* 出栈 */
public int Pop() { public int Pop() {
int num = Peek(); int num = Peek();
stackPeek = stackPeek.next; stackPeek = stackPeek!.next;
stkSize--; stkSize--;
return num; return num;
} }
@ -556,18 +556,18 @@ comments: true
public int Peek() { public int Peek() {
if (IsEmpty()) if (IsEmpty())
throw new Exception(); throw new Exception();
return stackPeek.val; return stackPeek!.val;
} }
/* 将 List 转化为 Array 并返回 */ /* 将 List 转化为 Array 并返回 */
public int[] ToArray() { public int[] ToArray() {
if (stackPeek == null) if (stackPeek == null)
return Array.Empty<int>(); return [];
ListNode node = stackPeek; ListNode? node = stackPeek;
int[] res = new int[Size()]; int[] res = new int[Size()];
for (int i = res.Length - 1; i >= 0; i--) { for (int i = res.Length - 1; i >= 0; i--) {
res[i] = node.val; res[i] = node!.val;
node = node.next; node = node.next;
} }
return res; return res;
@ -1237,10 +1237,10 @@ comments: true
```csharp title="array_stack.cs" ```csharp title="array_stack.cs"
/* 基于数组实现的栈 */ /* 基于数组实现的栈 */
class ArrayStack { class ArrayStack {
private readonly List<int> stack; List<int> stack;
public ArrayStack() { public ArrayStack() {
// 初始化列表(动态数组) // 初始化列表(动态数组)
stack = new(); stack = [];
} }
/* 获取栈的长度 */ /* 获取栈的长度 */
@ -1276,7 +1276,7 @@ comments: true
/* 将 List 转化为 Array 并返回 */ /* 将 List 转化为 Array 并返回 */
public int[] ToArray() { public int[] ToArray() {
return stack.ToArray(); return [.. stack];
} }
} }
``` ```

View File

@ -61,7 +61,7 @@ comments: true
```csharp title="" ```csharp title=""
/* 二叉树的数组表示 */ /* 二叉树的数组表示 */
// 使用 int? 可空类型 ,就可以使用 null 来标记空位 // 使用 int? 可空类型 ,就可以使用 null 来标记空位
int?[] tree = { 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 }; int?[] tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15];
``` ```
=== "Go" === "Go"
@ -410,13 +410,8 @@ comments: true
```csharp title="array_binary_tree.cs" ```csharp title="array_binary_tree.cs"
/* 数组表示下的二叉树类 */ /* 数组表示下的二叉树类 */
class ArrayBinaryTree { class ArrayBinaryTree(List<int?> arr) {
private readonly List<int?> tree; List<int?> tree = new(arr);
/* 构造方法 */
public ArrayBinaryTree(List<int?> arr) {
tree = new List<int?>(arr);
}
/* 节点数量 */ /* 节点数量 */
public int Size() { public int Size() {
@ -448,50 +443,50 @@ comments: true
/* 层序遍历 */ /* 层序遍历 */
public List<int> LevelOrder() { public List<int> LevelOrder() {
List<int> res = new(); List<int> res = [];
// 直接遍历数组 // 直接遍历数组
for (int i = 0; i < Size(); i++) { for (int i = 0; i < Size(); i++) {
if (Val(i).HasValue) if (Val(i).HasValue)
res.Add(Val(i).Value); res.Add(Val(i)!.Value);
} }
return res; return res;
} }
/* 深度优先遍历 */ /* 深度优先遍历 */
private void DFS(int i, string order, List<int> res) { void DFS(int i, string order, List<int> res) {
// 若为空位,则返回 // 若为空位,则返回
if (!Val(i).HasValue) if (!Val(i).HasValue)
return; return;
// 前序遍历 // 前序遍历
if (order == "pre") if (order == "pre")
res.Add(Val(i).Value); res.Add(Val(i)!.Value);
DFS(Left(i), order, res); DFS(Left(i), order, res);
// 中序遍历 // 中序遍历
if (order == "in") if (order == "in")
res.Add(Val(i).Value); res.Add(Val(i)!.Value);
DFS(Right(i), order, res); DFS(Right(i), order, res);
// 后序遍历 // 后序遍历
if (order == "post") if (order == "post")
res.Add(Val(i).Value); res.Add(Val(i)!.Value);
} }
/* 前序遍历 */ /* 前序遍历 */
public List<int> PreOrder() { public List<int> PreOrder() {
List<int> res = new(); List<int> res = [];
DFS(0, "pre", res); DFS(0, "pre", res);
return res; return res;
} }
/* 中序遍历 */ /* 中序遍历 */
public List<int> InOrder() { public List<int> InOrder() {
List<int> res = new(); List<int> res = [];
DFS(0, "in", res); DFS(0, "in", res);
return res; return res;
} }
/* 后序遍历 */ /* 后序遍历 */
public List<int> PostOrder() { public List<int> PostOrder() {
List<int> res = new(); List<int> res = [];
DFS(0, "post", res); DFS(0, "post", res);
return res; return res;
} }

View File

@ -71,12 +71,11 @@ AVL 树既是二叉搜索树也是平衡二叉树,同时满足这两类二叉
```csharp title="" ```csharp title=""
/* AVL 树节点类 */ /* AVL 树节点类 */
class TreeNode { class TreeNode(int? x) {
public int val; // 节点值 public int? val = x; // 节点值
public int height; // 节点高度 public int height; // 节点高度
public TreeNode? left; // 左子节点 public TreeNode? left; // 左子节点引用
public TreeNode? right; // 右子节点 public TreeNode? right; // 右子节点引用
public TreeNode(int x) { val = x; }
} }
``` ```
@ -689,7 +688,7 @@ AVL 树的特点在于“旋转”操作,它能够在不影响二叉树的中
```csharp title="avl_tree.cs" ```csharp title="avl_tree.cs"
/* 右旋操作 */ /* 右旋操作 */
TreeNode? RightRotate(TreeNode? node) { TreeNode? RightRotate(TreeNode? node) {
TreeNode? child = node.left; TreeNode? child = node?.left;
TreeNode? grandChild = child?.right; TreeNode? grandChild = child?.right;
// 以 child 为原点,将 node 向右旋转 // 以 child 为原点,将 node 向右旋转
child.right = node; child.right = node;
@ -926,7 +925,7 @@ AVL 树的特点在于“旋转”操作,它能够在不影响二叉树的中
```csharp title="avl_tree.cs" ```csharp title="avl_tree.cs"
/* 左旋操作 */ /* 左旋操作 */
TreeNode? LeftRotate(TreeNode? node) { TreeNode? LeftRotate(TreeNode? node) {
TreeNode? child = node.right; TreeNode? child = node?.right;
TreeNode? grandChild = child?.left; TreeNode? grandChild = child?.left;
// 以 child 为原点,将 node 向左旋转 // 以 child 为原点,将 node 向左旋转
child.left = node; child.left = node;
@ -1236,23 +1235,23 @@ AVL 树的特点在于“旋转”操作,它能够在不影响二叉树的中
int balanceFactorInt = BalanceFactor(node); int balanceFactorInt = BalanceFactor(node);
// 左偏树 // 左偏树
if (balanceFactorInt > 1) { if (balanceFactorInt > 1) {
if (BalanceFactor(node.left) >= 0) { if (BalanceFactor(node?.left) >= 0) {
// 右旋 // 右旋
return RightRotate(node); return RightRotate(node);
} else { } else {
// 先左旋后右旋 // 先左旋后右旋
node.left = LeftRotate(node?.left); node!.left = LeftRotate(node!.left);
return RightRotate(node); return RightRotate(node);
} }
} }
// 右偏树 // 右偏树
if (balanceFactorInt < -1) { if (balanceFactorInt < -1) {
if (BalanceFactor(node.right) <= 0) { if (BalanceFactor(node?.right) <= 0) {
// 左旋 // 左旋
return LeftRotate(node); return LeftRotate(node);
} else { } else {
// 先右旋后左旋 // 先右旋后左旋
node.right = RightRotate(node?.right); node!.right = RightRotate(node!.right);
return LeftRotate(node); return LeftRotate(node);
} }
} }
@ -2059,7 +2058,7 @@ AVL 树的节点插入操作与二叉搜索树在主体上类似。唯一的区
while (temp.left != null) { while (temp.left != null) {
temp = temp.left; temp = temp.left;
} }
node.right = RemoveHelper(node.right, temp.val); node.right = RemoveHelper(node.right, temp.val!.Value);
node.val = temp.val; node.val = temp.val;
} }
} }

View File

@ -980,7 +980,7 @@ comments: true
TreeNode? child = cur.left ?? cur.right; TreeNode? child = cur.left ?? cur.right;
// 删除节点 cur // 删除节点 cur
if (cur != root) { if (cur != root) {
if (pre.left == cur) if (pre!.left == cur)
pre.left = child; pre.left = child;
else else
pre.right = child; pre.right = child;
@ -997,7 +997,7 @@ comments: true
tmp = tmp.left; tmp = tmp.left;
} }
// 递归删除节点 tmp // 递归删除节点 tmp
Remove(tmp.val); Remove(tmp.val!.Value);
// 用 tmp 覆盖 cur // 用 tmp 覆盖 cur
cur.val = tmp.val; cur.val = tmp.val;
} }

View File

@ -45,11 +45,10 @@ comments: true
```csharp title="" ```csharp title=""
/* 二叉树节点类 */ /* 二叉树节点类 */
class TreeNode { class TreeNode(int? x) {
int val; // 节点值 public int? val = x; // 节点值
TreeNode? left; // 左子节点引用 public TreeNode? left; // 左子节点引用
TreeNode? right; // 右子节点引用 public TreeNode? right; // 右子节点引用
TreeNode(int x) { val = x; }
} }
``` ```

View File

@ -96,10 +96,10 @@ comments: true
Queue<TreeNode> queue = new(); Queue<TreeNode> queue = new();
queue.Enqueue(root); queue.Enqueue(root);
// 初始化一个列表,用于保存遍历序列 // 初始化一个列表,用于保存遍历序列
List<int> list = new(); List<int> list = [];
while (queue.Count != 0) { while (queue.Count != 0) {
TreeNode node = queue.Dequeue(); // 队列出队 TreeNode node = queue.Dequeue(); // 队列出队
list.Add(node.val); // 保存节点值 list.Add(node.val!.Value); // 保存节点值
if (node.left != null) if (node.left != null)
queue.Enqueue(node.left); // 左子节点入队 queue.Enqueue(node.left); // 左子节点入队
if (node.right != null) if (node.right != null)
@ -449,7 +449,7 @@ comments: true
void PreOrder(TreeNode? root) { void PreOrder(TreeNode? root) {
if (root == null) return; if (root == null) return;
// 访问优先级:根节点 -> 左子树 -> 右子树 // 访问优先级:根节点 -> 左子树 -> 右子树
list.Add(root.val); list.Add(root.val!.Value);
PreOrder(root.left); PreOrder(root.left);
PreOrder(root.right); PreOrder(root.right);
} }
@ -459,7 +459,7 @@ comments: true
if (root == null) return; if (root == null) return;
// 访问优先级:左子树 -> 根节点 -> 右子树 // 访问优先级:左子树 -> 根节点 -> 右子树
InOrder(root.left); InOrder(root.left);
list.Add(root.val); list.Add(root.val!.Value);
InOrder(root.right); InOrder(root.right);
} }
@ -469,7 +469,7 @@ comments: true
// 访问优先级:左子树 -> 右子树 -> 根节点 // 访问优先级:左子树 -> 右子树 -> 根节点
PostOrder(root.left); PostOrder(root.left);
PostOrder(root.right); PostOrder(root.right);
list.Add(root.val); list.Add(root.val!.Value);
} }
``` ```