m1okgoodyes

BinaryTree

Apr 3rd, 2022
1,028
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.86 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7.  
  8. namespace Generics
  9. {
  10.     public class BinaryTree<T> : IEnumerable<T>
  11.     {
  12.         public T Value { get; private set; }//значение в ячейках
  13.  
  14.         private bool isFool = false;//добавлен ли
  15.  
  16.         public BinaryTree<T> Left { get; private set; }
  17.  
  18.         public BinaryTree<T> Right { get; private set; }
  19.  
  20.         public void Add(T value)
  21.         {
  22.             if (!isFool)
  23.             {
  24.                 Value = value;
  25.                 isFool = true;
  26.             }
  27.             else
  28.             {
  29.                 AddNextTree(value);
  30.             }
  31.         }
  32.         private void AddNextTree(T value)
  33.         {
  34.             if (value.GetHashCode() <= Value.GetHashCode())
  35.             {
  36.                 if (Left == null)
  37.                     Left = new BinaryTree<T>();
  38.                 Left.Add(value);
  39.             }
  40.  
  41.             if (value.GetHashCode() > Value.GetHashCode())
  42.             {
  43.                 if (Right == null)
  44.                     Right = new BinaryTree<T>();
  45.                 Right.Add(value);
  46.             }
  47.         }
  48.  
  49.         public IEnumerator<T> GetEnumerator()
  50.         {
  51.             if (Left != null)
  52.                 foreach (var left in Left)
  53.                 {
  54.                     if (Left.isFool)
  55.                         yield return left;
  56.                 }
  57.  
  58.             if (isFool)
  59.                 yield return Value;
  60.  
  61.             if (Right != null)
  62.                 foreach (var right in Right)
  63.                 {
  64.                     if (Right.isFool)
  65.                         yield return right;
  66.                 }
  67.         }
  68.  
  69.         IEnumerator IEnumerable.GetEnumerator()
  70.         {
  71.             return GetEnumerator();
  72.         }
  73.     }
  74.  
  75.    
  76. }
Advertisement
Add Comment
Please, Sign In to add comment