LeetCode 數組轉二叉樹 C#

來源:互聯網
上載者:User

標籤:tac   ref   stack   tree   lan   ret   null   order   val   

把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#

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.