Facebook
From C#DOBRE, 5 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 193
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace ConsoleApp15
  5. {
  6.     public class Wezel<T>
  7.     {
  8.         public Wezel<T> Rodzic;
  9.         public Wezel<T> lewy;
  10.         public Wezel<T> prawy;
  11.         public int numer;
  12.         public T wartosc;
  13.         private object rodzic;
  14.  
  15.         public Wezel(int numer, T wartosc)
  16.         {
  17.             this.numer = numer;
  18.             this.wartosc = wartosc;
  19.         }
  20.  
  21.         public void DodajDziecko(Wezel<T>nowy)
  22.         {
  23.             if (nowy.numer % 2 == 0) this.lewy = nowy;
  24.             else this.prawy = nowy;
  25.         }
  26.     }
  27.  
  28.     public class Drzewo<T>
  29.     {
  30.         Wezel<T> root;
  31.         int length;
  32.  
  33.         public static List<int> DrogaDoRodzica(int numer)
  34.         {
  35.  
  36.             if (numer < 2) throw new Exception("Numer musi być większy równy niż 2");
  37.  
  38.             List<int> wynik = new List<int>();
  39.             numer = numer / 2;
  40.  
  41.             while(numer > 1)
  42.             {
  43.                 wynik.Add(numer % 2);
  44.                 numer = numer / 2;
  45.  
  46.             }
  47.             wynik.Reverse();
  48.  
  49.             return wynik;
  50.         }
  51.  
  52.         public Wezel<T> znajdzRodzica(int numer)
  53.         {
  54.  
  55.             var droga = Drzewo<T>.DrogaDoRodzica(numer);
  56.             Wezel<T> rodzic = this.root;
  57.  
  58.             for(int i = 0; i < droga.Count; i++)
  59.             {
  60.                 if (droga[i] == 0) rodzic = rodzic.lewy;
  61.                 else rodzic = rodzic.prawy;
  62.  
  63.             }
  64.  
  65.             return rodzic;
  66.         }
  67.  
  68.         public void Push(T wartosc)
  69.         {
  70.             Wezel<T> nowy = new Wezel<T>(length+1, wartosc);
  71.  
  72.             length++;
  73.             if ((length - 1) == 0)
  74.             {
  75.                 this.root = nowy;
  76.                 return;
  77.             }
  78.  
  79.             var rodzic = this.znajdzRodzica(nowy.numer);
  80.             rodzic.DodajDziecko(nowy);
  81.  
  82.         }
  83.  
  84.     }
  85.  
  86.  
  87.     class Program
  88.     {
  89.         static void Main(string[] args)
  90.         {
  91.             Drzewo<int> d = new Drzewo<int>();
  92.             d.Push(5);
  93.             d.Push(5);
  94.             d.Push(5);
  95.             d.Push(5);
  96.             d.Push(5);
  97.         }
  98.     }
  99. }
  100.