hello-algo/codes/csharp/include/TreeNode.cs

99 lines
2.6 KiB
C#
Raw Normal View History

/**
* File: TreeNode.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
2022-12-23 15:42:02 +08:00
namespace hello_algo.include
{
public class TreeNode
{
2022-12-24 16:15:41 +08:00
public int val; // 结点值
2022-12-23 15:42:02 +08:00
public int height; // 结点高度
public TreeNode? left; // 左子结点引用
public TreeNode? right; // 右子结点引用
2022-12-24 16:15:41 +08:00
public TreeNode(int x)
2022-12-23 15:42:02 +08:00
{
val = x;
}
/**
* Generate a binary tree with an array
* @param arr
* @return
*/
2022-12-24 16:15:41 +08:00
public static TreeNode? ArrToTree(int?[] arr)
2022-12-23 15:42:02 +08:00
{
2022-12-24 16:15:41 +08:00
if (arr.Length == 0 || arr[0] == null)
2022-12-23 15:42:02 +08:00
return null;
2022-12-24 16:15:41 +08:00
TreeNode root = new TreeNode((int) arr[0]);
2022-12-23 15:42:02 +08:00
Queue<TreeNode> queue = new Queue<TreeNode>();
queue.Enqueue(root);
int i = 1;
while (queue.Count!=0)
{
TreeNode node = queue.Dequeue();
if (arr[i] != null)
{
2022-12-24 16:15:41 +08:00
node.left = new TreeNode((int) arr[i]);
2022-12-23 15:42:02 +08:00
queue.Enqueue(node.left);
}
i++;
if (arr[i] != null)
{
2022-12-24 16:15:41 +08:00
node.right = new TreeNode((int) arr[i]);
2022-12-23 15:42:02 +08:00
queue.Enqueue(node.right);
}
i++;
}
return root;
}
/**
* Serialize a binary tree to a list
* @param root
* @return
*/
2022-12-24 16:15:41 +08:00
public static List<int?> TreeToList(TreeNode root)
2022-12-23 15:42:02 +08:00
{
List<int?> list = new();
if (root == null) return list;
Queue<TreeNode?> queue = new();
while (queue.Count != 0)
{
TreeNode? node = queue.Dequeue();
if (node != null)
{
list.Add(node.val);
queue.Enqueue(node.left);
queue.Enqueue(node.right);
}
else
{
list.Add(null);
}
}
return list;
}
/**
* Get a tree node with specific value in a binary tree
* @param root
* @param val
* @return
*/
2022-12-24 16:15:41 +08:00
public static TreeNode? GetTreeNode(TreeNode? root, int val)
2022-12-23 15:42:02 +08:00
{
if (root == null)
return null;
if (root.val == val)
return root;
2022-12-24 16:15:41 +08:00
TreeNode? left = GetTreeNode(root.left, val);
TreeNode? right = GetTreeNode(root.right, val);
2022-12-23 15:42:02 +08:00
return left != null ? left : right;
}
}
}