This commit is contained in:
krahets
2023-10-08 01:43:28 +08:00
parent 3d2d669b43
commit baac2d11a7
52 changed files with 999 additions and 625 deletions
+28 -28
View File
@@ -411,7 +411,7 @@ comments: true
```csharp title="array_binary_tree.cs"
/* 数组表示下的二叉树类 */
class ArrayBinaryTree {
private List<int?> tree;
private readonly List<int?> tree;
/* 构造方法 */
public ArrayBinaryTree(List<int?> arr) {
@@ -419,80 +419,80 @@ comments: true
}
/* 节点数量 */
public int size() {
public int Size() {
return tree.Count;
}
/* 获取索引为 i 节点的值 */
public int? val(int i) {
public int? Val(int i) {
// 若索引越界,则返回 null ,代表空位
if (i < 0 || i >= size())
if (i < 0 || i >= Size())
return null;
return tree[i];
}
/* 获取索引为 i 节点的左子节点的索引 */
public int left(int i) {
public int Left(int i) {
return 2 * i + 1;
}
/* 获取索引为 i 节点的右子节点的索引 */
public int right(int i) {
public int Right(int i) {
return 2 * i + 2;
}
/* 获取索引为 i 节点的父节点的索引 */
public int parent(int i) {
public int Parent(int i) {
return (i - 1) / 2;
}
/* 层序遍历 */
public List<int> levelOrder() {
List<int> res = new List<int>();
public List<int> LevelOrder() {
List<int> res = new();
// 直接遍历数组
for (int i = 0; i < size(); i++) {
if (val(i).HasValue)
res.Add(val(i).Value);
for (int i = 0; i < Size(); i++) {
if (Val(i).HasValue)
res.Add(Val(i).Value);
}
return res;
}
/* 深度优先遍历 */
private void dfs(int i, string order, List<int> res) {
private void Dfs(int i, string order, List<int> res) {
// 若为空位,则返回
if (!val(i).HasValue)
if (!Val(i).HasValue)
return;
// 前序遍历
if (order == "pre")
res.Add(val(i).Value);
dfs(left(i), order, res);
res.Add(Val(i).Value);
Dfs(Left(i), order, res);
// 中序遍历
if (order == "in")
res.Add(val(i).Value);
dfs(right(i), order, res);
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>();
dfs(0, "pre", res);
public List<int> PreOrder() {
List<int> res = new();
Dfs(0, "pre", res);
return res;
}
/* 中序遍历 */
public List<int> inOrder() {
List<int> res = new List<int>();
dfs(0, "in", res);
public List<int> InOrder() {
List<int> res = new();
Dfs(0, "in", res);
return res;
}
/* 后序遍历 */
public List<int> postOrder() {
List<int> res = new List<int>();
dfs(0, "post", res);
public List<int> PostOrder() {
List<int> res = new();
Dfs(0, "post", res);
return res;
}
}