首页 > 代码库 > LeetCode 数组转二叉树 C#

LeetCode 数组转二叉树 C#

把LeetCode二叉树题目的测试数组,转换成二叉树
  1. class TreeNode {
  2. public int val;
  3. public TreeNode left;
  4. public TreeNode right;
  5. public TreeNode(int x) { val = x; }
  6. }
  7. class Tree {
  8. public static TreeNode CreateNode(int? val) {
  9. if (val == null) return null;
  10. return new TreeNode((int)val);
  11. }
  12. public static TreeNode CreateTree(int?[] arr) {
  13. if (arr.Length <= 0 || arr[0] == null) {
  14. return null;
  15. }
  16. TreeNode root = Tree.CreateNode(arr[0]);
  17. Queue<TreeNode> queue = new Queue<TreeNode>();
  18. queue.Enqueue(root);
  19. int index = 1;
  20. while (queue.Count > 0) {
  21. TreeNode node = queue.Dequeue();
  22. if (index < arr.Length) {
  23. node.left = Tree.CreateNode(arr[index++]);
  24. queue.Enqueue(node.left);
  25. }
  26. if (index < arr.Length) {
  27. node.right = Tree.CreateNode(arr[index++]);
  28. queue.Enqueue(node.right);
  29. }
  30. }
  31. return root;
  32. }
  33. public static void Walk(TreeNode node, Action<TreeNode> func, TreeWalkType type) {
  34. if (node != null) {
  35. if (type == TreeWalkType.Pre) func(node);
  36. Walk(node.left, func, type);
  37. if (type == TreeWalkType.In) func(node);
  38. Walk(node.right, func, type);
  39. if (type == TreeWalkType.Post) func(node);
  40. }
  41. }
  42. public static void InOrderTreeWalk(TreeNode root, Action<TreeNode> func) {
  43. if (root == null) {
  44. return;
  45. }
  46. Stack<TreeNode> stack = new Stack<TreeNode>();
  47. TreeNode current = root;
  48. while (current != null) {
  49. stack.Push(current);
  50. current = current.left;
  51. }
  52. while (stack.Count != 0) {
  53. current = stack.Pop();
  54. func(current); //func
  55. TreeNode node = current.right;
  56. while (node != null) {
  57. stack.Push(node);
  58. node = node.left;
  59. }
  60. }
  61. }
  62. }
  63. enum TreeWalkType {
  64. Pre,
  65. In,
  66. Post
  67. }




null


LeetCode 数组转二叉树 C#