首页 > 代码库 > LeetCode 数组转二叉树 C#
LeetCode 数组转二叉树 C#
把LeetCode二叉树题目的测试数组,转换成二叉树
class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
class Tree {
public static TreeNode CreateNode(int? val) {
if (val == null) return null;
return new TreeNode((int)val);
}
public static TreeNode CreateTree(int?[] arr) {
if (arr.Length <= 0 || arr[0] == null) {
return null;
}
TreeNode root = Tree.CreateNode(arr[0]);
Queue<TreeNode> queue = new Queue<TreeNode>();
queue.Enqueue(root);
int index = 1;
while (queue.Count > 0) {
TreeNode node = queue.Dequeue();
if (index < arr.Length) {
node.left = Tree.CreateNode(arr[index++]);
queue.Enqueue(node.left);
}
if (index < arr.Length) {
node.right = Tree.CreateNode(arr[index++]);
queue.Enqueue(node.right);
}
}
return root;
}
public static void Walk(TreeNode node, Action<TreeNode> func, TreeWalkType type) {
if (node != null) {
if (type == TreeWalkType.Pre) func(node);
Walk(node.left, func, type);
if (type == TreeWalkType.In) func(node);
Walk(node.right, func, type);
if (type == TreeWalkType.Post) func(node);
}
}
public static void InOrderTreeWalk(TreeNode root, Action<TreeNode> func) {
if (root == null) {
return;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode current = root;
while (current != null) {
stack.Push(current);
current = current.left;
}
while (stack.Count != 0) {
current = stack.Pop();
func(current); //func
TreeNode node = current.right;
while (node != null) {
stack.Push(node);
node = node.left;
}
}
}
}
enum TreeWalkType {
Pre,
In,
Post
}
null
LeetCode 数组转二叉树 C#
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。