Danielos168

Wypisywanie zawartości drzewa

Jan 21st, 2020
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.48 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace zad3
  5. {
  6.     class Program
  7.     {
  8.         static void Main( string[] args )
  9.         {
  10.             Drzewo d = new Drzewo();
  11.             d.glowa = new Element( 10 );
  12.             d.glowa.DodajDzieci( new List<int>() { 2, 54, 6, 1, 65, 2 } );
  13.  
  14.             // Wypelnianie drzewa
  15.             foreach( Element e in d.glowa.dzieci )
  16.             {
  17.                 List<int> l = new List<int>();
  18.                 for( int i = 0; i < 3; i++ )
  19.                     l.Add( i + 1 );
  20.  
  21.                 e.DodajDzieci( l );
  22.  
  23.                 e.dzieci[ 0 ].DodajDzieci( new List<int>() { 100 } );
  24.                 e.dzieci[ 0 ].dzieci[ 0 ].DodajDzieci( new List<int>() { 200 } );
  25.             }
  26.  
  27.             d.Wyswietl();
  28.  
  29.             Console.ReadKey();
  30.         }
  31.  
  32.         class Drzewo
  33.         {
  34.             public Element glowa;
  35.  
  36.             public void Wyswietl()
  37.             {
  38.                 if( glowa == null ) return;
  39.  
  40.                 Queue<Element> q = new Queue<Element>();
  41.                 q.Enqueue( glowa );
  42.  
  43.                 while( q.Count > 0 )
  44.                 {
  45.                     foreach( Element e in q.Peek().dzieci )
  46.                         q.Enqueue( e );
  47.  
  48.                     Console.Write( q.Dequeue() + " " );
  49.                 }
  50.                 Console.WriteLine();
  51.             }
  52.         }
  53.  
  54.         class Element
  55.         {
  56.             public Element()
  57.             {
  58.                 wartosc = 0;
  59.                 dzieci = new List<Element>();
  60.             }
  61.             public Element( int w )
  62.             {
  63.                 wartosc = w;
  64.                 dzieci = new List<Element>();
  65.             }
  66.             public int wartosc;
  67.             public List<Element> dzieci;
  68.  
  69.             public void DodajDzieci( List<int> lista )
  70.             {
  71.                 foreach( int a in lista )
  72.                     dzieci.Add( new Element( a ) );
  73.             }
  74.  
  75.             public override string ToString()
  76.             {
  77.                 return wartosc.ToString();
  78.             }
  79.         }
  80.     }
  81. }
Add Comment
Please, Sign In to add comment