mirror of
https://github.com/krahets/hello-algo.git
synced 2026-02-09 05:44:13 +08:00
feat(csharp) .NET 8.0 code migration (#966)
* .net 8.0 migration * update docs * revert change * revert change and update appendix docs * remove static * Update binary_search_insertion.cs * Update binary_search_insertion.cs * Update binary_search_edge.cs * Update binary_search_insertion.cs * Update binary_search_edge.cs --------- Co-authored-by: Yudong Jin <krahets@163.com>
This commit is contained in:
@@ -7,13 +7,8 @@
|
||||
namespace hello_algo.chapter_tree;
|
||||
|
||||
/* 数组表示下的二叉树类 */
|
||||
public class ArrayBinaryTree {
|
||||
private readonly List<int?> tree;
|
||||
|
||||
/* 构造方法 */
|
||||
public ArrayBinaryTree(List<int?> arr) {
|
||||
tree = new List<int?>(arr);
|
||||
}
|
||||
public class ArrayBinaryTree(List<int?> arr) {
|
||||
List<int?> tree = new(arr);
|
||||
|
||||
/* 节点数量 */
|
||||
public int Size() {
|
||||
@@ -45,50 +40,50 @@ public class ArrayBinaryTree {
|
||||
|
||||
/* 层序遍历 */
|
||||
public List<int> LevelOrder() {
|
||||
List<int> res = new();
|
||||
List<int> res = [];
|
||||
// 直接遍历数组
|
||||
for (int i = 0; i < Size(); i++) {
|
||||
if (Val(i).HasValue)
|
||||
res.Add(Val(i).Value);
|
||||
res.Add(Val(i)!.Value);
|
||||
}
|
||||
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)
|
||||
return;
|
||||
// 前序遍历
|
||||
if (order == "pre")
|
||||
res.Add(Val(i).Value);
|
||||
res.Add(Val(i)!.Value);
|
||||
DFS(Left(i), order, res);
|
||||
// 中序遍历
|
||||
if (order == "in")
|
||||
res.Add(Val(i).Value);
|
||||
res.Add(Val(i)!.Value);
|
||||
DFS(Right(i), order, res);
|
||||
// 后序遍历
|
||||
if (order == "post")
|
||||
res.Add(Val(i).Value);
|
||||
res.Add(Val(i)!.Value);
|
||||
}
|
||||
|
||||
/* 前序遍历 */
|
||||
public List<int> PreOrder() {
|
||||
List<int> res = new();
|
||||
List<int> res = [];
|
||||
DFS(0, "pre", res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* 中序遍历 */
|
||||
public List<int> InOrder() {
|
||||
List<int> res = new();
|
||||
List<int> res = [];
|
||||
DFS(0, "in", res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* 后序遍历 */
|
||||
public List<int> PostOrder() {
|
||||
List<int> res = new();
|
||||
List<int> res = [];
|
||||
DFS(0, "post", res);
|
||||
return res;
|
||||
}
|
||||
@@ -99,9 +94,9 @@ public class array_binary_tree {
|
||||
public void Test() {
|
||||
// 初始化二叉树
|
||||
// 这里借助了一个从数组直接生成二叉树的函数
|
||||
List<int?> arr = new() { 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 };
|
||||
List<int?> arr = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15];
|
||||
|
||||
TreeNode root = TreeNode.ListToTree(arr);
|
||||
TreeNode? root = TreeNode.ListToTree(arr);
|
||||
Console.WriteLine("\n初始化二叉树\n");
|
||||
Console.WriteLine("二叉树的数组表示:");
|
||||
Console.WriteLine(arr.PrintList());
|
||||
|
||||
Reference in New Issue
Block a user