2022-12-23 18:28:17 +08:00
|
|
|
/**
|
|
|
|
* File: TreeNode.cs
|
|
|
|
* Created Time: 2022-12-23
|
|
|
|
* Author: haptear (haptear@hotmail.com)
|
|
|
|
*/
|
|
|
|
|
2023-04-24 04:20:51 +08:00
|
|
|
namespace hello_algo.utils;
|
2023-02-08 22:18:02 +08:00
|
|
|
|
2023-04-23 03:03:12 +08:00
|
|
|
/* 二叉树节点类 */
|
2023-11-26 23:18:44 +08:00
|
|
|
public class TreeNode(int? x) {
|
|
|
|
public int? val = x; // 节点值
|
|
|
|
public int height; // 节点高度
|
2023-04-09 04:32:17 +08:00
|
|
|
public TreeNode? left; // 左子节点引用
|
|
|
|
public TreeNode? right; // 右子节点引用
|
2023-02-08 22:18:02 +08:00
|
|
|
|
2023-07-20 18:54:40 +08:00
|
|
|
// 序列化编码规则请参考:
|
|
|
|
// https://www.hello-algo.com/chapter_tree/array_representation_of_tree/
|
|
|
|
// 二叉树的数组表示:
|
|
|
|
// [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15]
|
|
|
|
// 二叉树的链表表示:
|
|
|
|
// /——— 15
|
|
|
|
// /——— 7
|
|
|
|
// /——— 3
|
|
|
|
// | \——— 6
|
|
|
|
// | \——— 12
|
|
|
|
// ——— 1
|
|
|
|
// \——— 2
|
|
|
|
// | /——— 9
|
|
|
|
// \——— 4
|
|
|
|
// \——— 8
|
2022-12-23 15:42:02 +08:00
|
|
|
|
2023-07-20 18:54:40 +08:00
|
|
|
/* 将列表反序列化为二叉树:递归 */
|
2023-11-26 23:18:44 +08:00
|
|
|
static TreeNode? ListToTreeDFS(List<int?> arr, int i) {
|
2023-09-02 23:54:38 +08:00
|
|
|
if (i < 0 || i >= arr.Count || !arr[i].HasValue) {
|
2023-07-20 18:54:40 +08:00
|
|
|
return null;
|
2022-12-23 15:42:02 +08:00
|
|
|
}
|
2023-11-26 23:18:44 +08:00
|
|
|
TreeNode root = new(arr[i]) {
|
2023-10-08 01:33:46 +08:00
|
|
|
left = ListToTreeDFS(arr, 2 * i + 1),
|
|
|
|
right = ListToTreeDFS(arr, 2 * i + 2)
|
|
|
|
};
|
2023-02-08 22:18:02 +08:00
|
|
|
return root;
|
|
|
|
}
|
2022-12-23 15:42:02 +08:00
|
|
|
|
2023-07-20 18:54:40 +08:00
|
|
|
/* 将列表反序列化为二叉树 */
|
|
|
|
public static TreeNode? ListToTree(List<int?> arr) {
|
|
|
|
return ListToTreeDFS(arr, 0);
|
|
|
|
}
|
|
|
|
|
|
|
|
/* 将二叉树序列化为列表:递归 */
|
2023-11-26 23:18:44 +08:00
|
|
|
static void TreeToListDFS(TreeNode? root, int i, List<int?> res) {
|
2023-07-20 18:54:40 +08:00
|
|
|
if (root == null)
|
|
|
|
return;
|
|
|
|
while (i >= res.Count) {
|
|
|
|
res.Add(null);
|
2022-12-23 15:42:02 +08:00
|
|
|
}
|
2023-07-20 18:54:40 +08:00
|
|
|
res[i] = root.val;
|
|
|
|
TreeToListDFS(root.left, 2 * i + 1, res);
|
|
|
|
TreeToListDFS(root.right, 2 * i + 2, res);
|
|
|
|
}
|
|
|
|
|
|
|
|
/* 将二叉树序列化为列表 */
|
2023-10-08 01:33:46 +08:00
|
|
|
public static List<int?> TreeToList(TreeNode root) {
|
2023-11-26 23:18:44 +08:00
|
|
|
List<int?> res = [];
|
2023-07-20 18:54:40 +08:00
|
|
|
TreeToListDFS(root, 0, res);
|
|
|
|
return res;
|
2023-02-08 22:18:02 +08:00
|
|
|
}
|
2022-12-23 15:42:02 +08:00
|
|
|
}
|