You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
1.8 KiB
63 lines
1.8 KiB
2 years ago
|
/**
|
||
|
* File: TreeNode.cs
|
||
|
* Created Time: 2022-12-23
|
||
|
* Author: haptear (haptear@hotmail.com)
|
||
|
*/
|
||
|
|
||
2 years ago
|
namespace hello_algo.utils;
|
||
2 years ago
|
|
||
2 years ago
|
/* 二叉树节点类 */
|
||
|
public class TreeNode {
|
||
2 years ago
|
public int val; // 节点值
|
||
|
public int height; // 节点高度
|
||
|
public TreeNode? left; // 左子节点引用
|
||
|
public TreeNode? right; // 右子节点引用
|
||
2 years ago
|
|
||
2 years ago
|
public TreeNode(int x) {
|
||
2 years ago
|
val = x;
|
||
|
}
|
||
2 years ago
|
|
||
2 years ago
|
/* Generate a binary tree given an array */
|
||
|
public static TreeNode? ListToTree(List<int?> arr) {
|
||
2 years ago
|
if (arr.Count == 0 || arr[0] == null)
|
||
2 years ago
|
return null;
|
||
2 years ago
|
|
||
2 years ago
|
TreeNode root = new TreeNode(arr[0]!.Value);
|
||
2 years ago
|
Queue<TreeNode> queue = new Queue<TreeNode>();
|
||
|
queue.Enqueue(root);
|
||
|
int i = 0;
|
||
2 years ago
|
while (queue.Count != 0) {
|
||
2 years ago
|
TreeNode node = queue.Dequeue();
|
||
2 years ago
|
if (++i >= arr.Count) break;
|
||
2 years ago
|
if (arr[i] != null) {
|
||
2 years ago
|
node.left = new TreeNode((int)arr[i]);
|
||
|
queue.Enqueue(node.left);
|
||
|
}
|
||
2 years ago
|
if (++i >= arr.Count) break;
|
||
2 years ago
|
if (arr[i] != null) {
|
||
2 years ago
|
node.right = new TreeNode((int)arr[i]);
|
||
|
queue.Enqueue(node.right);
|
||
2 years ago
|
}
|
||
|
}
|
||
2 years ago
|
return root;
|
||
|
}
|
||
2 years ago
|
|
||
2 years ago
|
/* Serialize a binary tree to a list */
|
||
|
public static List<int?> TreeToList(TreeNode root) {
|
||
2 years ago
|
List<int?> list = new();
|
||
|
if (root == null) return list;
|
||
|
Queue<TreeNode?> queue = new();
|
||
2 years ago
|
while (queue.Count != 0) {
|
||
2 years ago
|
TreeNode? node = queue.Dequeue();
|
||
2 years ago
|
if (node != null) {
|
||
2 years ago
|
list.Add(node.val);
|
||
|
queue.Enqueue(node.left);
|
||
|
queue.Enqueue(node.right);
|
||
2 years ago
|
} else {
|
||
2 years ago
|
list.Add(null);
|
||
2 years ago
|
}
|
||
|
}
|
||
2 years ago
|
return list;
|
||
|
}
|
||
2 years ago
|
}
|