Advertisement
Guest User

zad 3 wypisz drzewo poziomami

a guest
Jan 22nd, 2020
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace Drzewo
  8. {
  9. class Drzewo
  10. {
  11. public Węzeł korzeń;
  12.  
  13.  
  14. public void WypiszPoziomami()
  15. {
  16. Queue kolejka = new Queue();
  17. Queue tmp = new Queue();
  18. kolejka.Enqueue(korzeń);
  19. int poziom = 0;
  20. Console.Write("Poziom: Węzły");
  21. Console.Write('\n');
  22. while (kolejka.Count != 0)
  23. {
  24. Console.Write(poziom + ": ");
  25. while (kolejka.Count != 0)
  26. {
  27. Węzeł temporary = (Węzeł)kolejka.Dequeue();
  28. Console.Write(temporary.wartosc + " ");
  29.  
  30. for (int j = 0; j < temporary.dzieci.Count; j++)
  31. {
  32. tmp.Enqueue(temporary.dzieci[j]);
  33. }
  34. }
  35. Console.Write('\n');
  36.  
  37. while(tmp.Count != 0)
  38. {
  39. kolejka.Enqueue(tmp.Dequeue());
  40. }
  41. poziom++;
  42. }
  43. }
  44.  
  45. public void WypiszPoziomamiUproszczone()
  46. {
  47. Queue kolejka = new Queue();
  48. kolejka.Enqueue(korzeń);
  49. while(kolejka.Count != 0)
  50. {
  51. Węzeł wypisywany = (Węzeł)kolejka.Dequeue();
  52. Węzeł doPorownania = wypisywany;
  53. Console.Write(wypisywany.wartosc + " ");
  54. }
  55. }
  56. }
  57.  
  58. class Węzeł
  59. {
  60. public string wartosc;
  61. public ArrayList dzieci;
  62.  
  63. public Węzeł(string wart)
  64. {
  65. wartosc = wart;
  66. dzieci = new ArrayList();
  67. }
  68. }
  69.  
  70.  
  71. class Program
  72. {
  73. public static void Dodaj(Węzeł k, Węzeł w)
  74. {
  75. k.dzieci.Add(w);
  76. }
  77.  
  78. static void Main(string[] args)
  79. {
  80. Drzewo drzewko = new Drzewo();
  81. Węzeł A = new Węzeł("A");
  82. Węzeł B = new Węzeł("B");
  83. Węzeł C = new Węzeł("C");
  84. Węzeł D = new Węzeł("D");
  85. Węzeł E = new Węzeł("E");
  86. Węzeł F = new Węzeł("F");
  87.  
  88. drzewko.korzeń = A;
  89. Dodaj(A, B);
  90. Dodaj(A, C);
  91. Dodaj(B, D);
  92. Dodaj(B, E);
  93. Dodaj(D, F);
  94.  
  95. drzewko.WypiszPoziomami();
  96. Console.ReadKey();
  97. }
  98. }
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement