Обход дерева в ширину - C#

Узнай цену своей работы

Формулировка задачи:

Здравстуйте! Есть реализация класса с деревьями, не могу написать метод для поуровневого обхода дерева итерациями (т.е. в ширину), чтобы возвращал коллекцию узлов, т.е. Node и всё это с yield. Код класса прилагается: (в нём я уже сделал один метод из другого задания)
Листинг программы
  1. class Tree
  2. {
  3. /// <summary>
  4. /// /////// 15
  5. /// </summary>
  6. /// <param name="node"></param>
  7. /// <returns></returns>
  8. public int[] GetIntInRec()
  9. {
  10. List<int> nodesList = new List<int>();
  11. GetIntInRec(this.root, nodesList);
  12. return nodesList.ToArray();
  13. }
  14. public void GetIntInRec(Node node, List<int> nodesList)
  15. {
  16. nodesList.Add(node.value);
  17. if (node.left != null)
  18. {
  19. GetIntInRec(node.left, nodesList);
  20. }
  21. if (node.right != null)
  22. {
  23. GetIntInRec(node.right, nodesList);
  24. }
  25. }
  26. /// <summary>
  27. /// /////// end15
  28. /// </summary>
  29. public class Node
  30. {
  31. public Node left;
  32. public Node right;
  33. public Node parent;
  34. public int value;
  35. public Node(int value, Node left = null, Node right = null)
  36. {
  37. this.value = value;
  38. if (left != null)
  39. {
  40. left.parent = this;
  41. }
  42. this.left = left;
  43. if (right != null)
  44. {
  45. right.parent = this;
  46. }
  47. this.right = right;
  48. }
  49. //если отладчик глючит, когда наводите на переменную типа Node или Tree,
  50. //то скорее всего в дереве циклическая ссылка, надо заккомментировать целиком этот метод (чтобы отладчик не падал),
  51. //починить место, из-за которого циклическая ссылка и раскомментировать обратно
  52. public override string ToString()
  53. {
  54. //return ToStringMultiline(); // надо смотреть, повернув голову налево, в отладчике ничего непонятно
  55. return ToStringSingleLine(); // в одну строку
  56. }
  57. public string ToStringSingleLine()
  58. {
  59. return ToStringLinear(this);
  60. }
  61. public string ToStringMultiline()
  62. {
  63. return ToStringMultiline(this);
  64. }
  65. static string ToStringLinear(Node node)
  66. {
  67. if (node == null)
  68. {
  69. return "_";
  70. }
  71. return string.Format("({0} {1} {2})",
  72. ToStringLinear(node.left),
  73. node.value,
  74. ToStringLinear(node.right)
  75. );
  76. }
  77. static string ToStringMultiline(Node node, string indent = "")
  78. {
  79. if (node == null)
  80. {
  81. return "";
  82. }
  83. return
  84. ToStringMultiline(node.right, indent + " ") +
  85. string.Format("{0}{1}\n", indent, node.value) +
  86. ToStringMultiline(node.left, indent + " ");
  87. }
  88. }
  89. Node root;
  90. public Tree(Node root = null)
  91. {
  92. this.root = root;
  93. }
  94. public override string ToString()
  95. {
  96. if (root == null)
  97. {
  98. return "_";
  99. }
  100. return root.ToString();
  101. }
  102. public string ToStringMultiline()
  103. {
  104. if (root == null)
  105. {
  106. return "_";
  107. }
  108. return root.ToStringMultiline();
  109. }
  110. public void CheckParents()
  111. {
  112. if (root == null)
  113. {
  114. return;
  115. }
  116. if (root.parent != null)
  117. {
  118. throw new Exception("root node has parent");
  119. }
  120. Action<Node, Node> go = null;
  121. go = (parent, node) =>
  122. {
  123. if (node == null)
  124. {
  125. return;
  126. }
  127. if (parent != node.parent)
  128. {
  129. throw new Exception(string.Format("{0} has wrong parent", node.value));
  130. }
  131. go(node, node.left);
  132. go(node, node.right);
  133. };
  134. go(root, root.left);
  135. go(root, root.right);
  136. }
  137. }
  138. class TreeDebug
  139. {
  140. public void Debug()
  141. {
  142. DebugToString();
  143. DebugCheckParents();
  144. }
  145. static Tree.Node N(Tree.Node left, int value, Tree.Node right)
  146. {
  147. return new Tree.Node(value, left, right);
  148. }
  149. void DebugToString()
  150. {
  151. var root_node = N(N(null, 2, N(null, 3, null)), 4, N(N(null, 5, null), 6, null));
  152. var tree = new Tree(root_node);
  153. tree.CheckParents();
  154. Console.WriteLine(tree);
  155. Console.WriteLine(root_node.ToStringMultiline());
  156. var empty_tree = new Tree();
  157. empty_tree.CheckParents();
  158. Console.WriteLine(empty_tree);
  159. Console.WriteLine("15. in int array rec: ");
  160. int[] massiv = tree.GetIntInRec();
  161. for (int i = 0; i < massiv.Count(); i++)
  162. {
  163. Console.Write(massiv[i] + " ");
  164. }
  165. }
  166. void DebugCheckParents()
  167. {
  168. var root_node = N(N(null, 2, null), 1, null);
  169. root_node.left.parent = N(null, 23, null);
  170. var bad_tree = new Tree(root_node);
  171. try
  172. {
  173. bad_tree.CheckParents();
  174. }
  175. catch (Exception e)
  176. {
  177. Console.WriteLine(e.Message);
  178. }
  179. }
  180. }

Решение задачи: «Обход дерева в ширину»

textual
Листинг программы
  1. public IEnumerable<Node> LevelOrderTraversal()
  2. {
  3.    if (root == null)
  4.       yield break;
  5.  
  6.    var queue = new Queue<Node>();
  7.    queue.Enqueue(root);
  8.  
  9.    while (queue.Count > 0)
  10.    {
  11.       var node = queue.Dequeue();
  12.       yield return node;
  13.  
  14.       if (node.left != null)
  15.          queue.Enqueue(node.left);
  16.       if (node.right != null)
  17.          queue.Enqueue(node.right);
  18.    }
  19. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

15   голосов , оценка 3.6 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы