LeetCode 数组转二叉树 C#

把LeetCode二叉树题目的测试数组,转换成二叉树

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace Algorithm {
  7. class TreeNode {
  8. public int val;
  9. public TreeNode left;
  10. public TreeNode right;
  11. public TreeNode(int x) { val = x; }
  12. }
  13. class Tree {
  14. public static TreeNode CreateNode(int? val) {
  15. if (val == null) return null;
  16. return new TreeNode((int)val);
  17. }
  18. public static TreeNode CreateTree(int?[] arr) {
  19. if (arr.Length <= 0 || arr[0] == null) {
  20. return null;
  21. }
  22. TreeNode root = Tree.CreateNode(arr[0]);
  23. Queue<TreeNode> queue = new Queue<TreeNode>();
  24. queue.Enqueue(root);
  25. int index = 1;
  26. while (queue.Count > 0) {
  27. TreeNode node = queue.Dequeue();
  28. if (node == null) continue;
  29. if (index < arr.Length) {
  30. node.left = Tree.CreateNode(arr[index++]);
  31. queue.Enqueue(node.left);
  32. }
  33. if (index < arr.Length) {
  34. node.right = Tree.CreateNode(arr[index++]);
  35. queue.Enqueue(node.right);
  36. }
  37. }
  38. return root;
  39. }
  40. public static void Walk(TreeNode node, Action<TreeNode> func, TreeWalkType type) {
  41. if (node != null) {
  42. if (type == TreeWalkType.Pre) func(node);
  43. Walk(node.left, func, type);
  44. if (type == TreeWalkType.In) func(node);
  45. Walk(node.right, func, type);
  46. if (type == TreeWalkType.Post) func(node);
  47. }
  48. }
  49. //非递归,广度优先遍历
  50. public static void BFSWalk(TreeNode root, Action<TreeNode> func) {
  51. if (root == null) return;
  52. Queue<TreeNode> queue = new Queue<TreeNode>();
  53. queue.Enqueue(root);
  54. while (queue.Count > 0) {
  55. TreeNode node = queue.Dequeue();
  56. func(node);
  57. if (node.left != null) queue.Enqueue(node.left);
  58. if (node.right != null) queue.Enqueue(node.right);
  59. }
  60. }
  61. //非递归,中序遍历
  62. public static void InOrderTreeWalk(TreeNode root, Action<TreeNode> func) {
  63. if (root == null) {
  64. return;
  65. }
  66. Stack<TreeNode> stack = new Stack<TreeNode>();
  67. TreeNode current = root;
  68. while (current != null) {
  69. stack.Push(current);
  70. current = current.left;
  71. }
  72. while (stack.Count != 0) {
  73. current = stack.Pop();
  74. func(current); //func
  75. TreeNode node = current.right;
  76. while (node != null) {
  77. stack.Push(node);
  78. node = node.left;
  79. }
  80. }
  81. }
  82. }
  83. enum TreeWalkType {
  84. Pre,
  85. In,
  86. Post
  87. }
  88. }






posted @ 2017-06-17 21:48  xiejunzhao  阅读(855)  评论(0编辑  收藏  举报