Advertisement
myloyo

21 деревья 1, 2, 3

May 3rd, 2024 (edited)
755
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 12.51 KB | None | 0 0
  1. //класс дерева
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Security.Cryptography.X509Certificates;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10.  
  11. namespace Myloyorrrr
  12. {
  13.     public class BinaryTree //класс, реализующий АТД «дерево бинарного поиска»
  14.     {
  15.         //вложенный класс, отвечающий за узлы и операции допустимы для дерева бинарного
  16.         //поиска
  17.         private class Node
  18.         {
  19.             public object inf; //информационное поле
  20.             public Node left; //ссылка на левое поддерево
  21.             public Node right; //ссылка на правое поддерево
  22.                                //конструктор вложенного класса, создает узел дерева
  23.             public Node(object nodeInf)
  24.             {
  25.                 inf = nodeInf;
  26.                 left = null;
  27.                 right = null;
  28.             }
  29.             //добавляет узел в дерево так, чтобы дерево оставалось деревом бинарного поиска
  30.             public static void Add(ref Node r, object nodeInf)
  31.             {
  32.                 if (r == null)
  33.                 {
  34.                     r = new Node(nodeInf);
  35.                 }
  36.                 else
  37.                 {
  38.                     if (((IComparable)(r.inf)).CompareTo(nodeInf) > 0)
  39.                     {
  40.                         Add(ref r.left, nodeInf);
  41.                     }
  42.                     else
  43.                     {
  44.                         Add(ref r.right, nodeInf);
  45.                     }
  46.                 }
  47.             }
  48.             public static void Preorder(Node r) //прямой обход дерева
  49.             {
  50.                 if (r != null)
  51.                 {
  52.                     Console.Write("{0} ", r.inf);
  53.                     Preorder(r.left);
  54.                     Preorder(r.right);
  55.                 }
  56.             }
  57.             public static void Inorder(Node r) //симметричный обход дерева
  58.             {
  59.                 if (r != null)
  60.                 {
  61.                     Inorder(r.left);
  62.                     Console.Write("{0} ", r.inf);
  63.                     Inorder(r.right);
  64.                 }
  65.             }
  66.             public static void Postorder(Node r) //обратный обход дерева
  67.             {
  68.                 if (r != null)
  69.                 {
  70.                     Postorder(r.left);
  71.                     Postorder(r.right);
  72.                     Console.Write("{0} ", r.inf);
  73.                 }
  74.             }
  75.  
  76.             public static int CountNodes(Node x)
  77.             {
  78.                 int l = CountNodes(x.left);
  79.                 int r = CountNodes(x.right);
  80.  
  81.                 return 1 + l + r;
  82.             }
  83.  
  84.             private static int Height(Node node)
  85.             {
  86.                 if (node == null)
  87.                     return 0;
  88.  
  89.                 return Math.Max(Height(node.left), Height(node.right)) + 1;
  90.             }
  91.  
  92.             public static bool IsBalanced(Node node)
  93.             {
  94.                 if (node == null)
  95.                     return true;
  96.  
  97.                 int leftHeight = Height(node.left);
  98.                 int rightHeight = Height(node.right);
  99.  
  100.                 // Проверяем разницу высот левого и правого поддеревьев
  101.                 if (Math.Abs(leftHeight - rightHeight) <= 1 && IsBalanced(node.left) && IsBalanced(node.right))
  102.                     return true;
  103.  
  104.                 return false;
  105.             }
  106.             public static void PrintNodes(Node node, int currentlvl, int targetlvl, ref int cnt)
  107.             {
  108.                 if (node == null)
  109.                 {
  110.                     return;
  111.                 }
  112.                 if(currentlvl == targetlvl)
  113.                 {
  114.                     cnt++;
  115.                     return;
  116.                 }
  117.                 else if(currentlvl < targetlvl)
  118.                 {
  119.                     cnt++;
  120.                     PrintNodes(node.left, currentlvl + 1, targetlvl, ref cnt);
  121.                     PrintNodes(node.right, currentlvl + 1, targetlvl, ref cnt);
  122.                 }
  123.             }
  124.  
  125.             //поиск ключевого узла в дереве
  126.             public static void Search(Node r, object key, out Node item)
  127.             {
  128.                 if (r == null)
  129.                 {
  130.                     item = null;
  131.                 }
  132.                 else
  133.                 {
  134.                     if (((IComparable)(r.inf)).CompareTo(key) == 0)
  135.                     {
  136.                         item = r;
  137.                     }
  138.                     else
  139.                     {
  140.                         if (((IComparable)(r.inf)).CompareTo(key) > 0)
  141.                         {
  142.                             Search(r.left, key, out item);
  143.                         }
  144.                         else
  145.                         {
  146.                             Search(r.right, key, out item);
  147.                         }
  148.                     }
  149.                 }
  150.             }
  151.             //методы Del и Delete позволяют удалить узел в дереве так, чтобы дерево при этом
  152.             //оставалось деревом бинарного поиска
  153.             private static void Del(Node t, ref Node tr)
  154.             {
  155.                 if (tr.right != null)
  156.                 {
  157.                     Del(t, ref tr.right);
  158.                 }
  159.                 else
  160.                 {
  161.                     t.inf = tr.inf;
  162.                     tr = tr.left;
  163.                 }
  164.             }
  165.             public static void Delete(ref Node t, object key)
  166.             {
  167.                 if (t == null)
  168.                 {
  169.                     throw new Exception("Данное значение в дереве отсутствует");
  170.                 }
  171.                 else
  172.                 {
  173.                     if (((IComparable)(t.inf)).CompareTo(key) > 0)
  174.                     {
  175.                         Delete(ref t.left, key);
  176.                     }
  177.                     else
  178.                     {
  179.                         if (((IComparable)(t.inf)).CompareTo(key) < 0)
  180.                         {
  181.                             Delete(ref t.right, key);
  182.                         }
  183.                         else
  184.                         {
  185.                             if (t.left == null)
  186.                             {
  187.                                 t = t.right;
  188.                             }
  189.                             else
  190.                             {
  191.                                 if (t.right == null)
  192.                                 {
  193.                                     t = t.left;
  194.                                 }
  195.                                 else
  196.                                 {
  197.                                     Del(t, ref t.left);
  198.                                 }
  199.                             }
  200.                         }
  201.                     }
  202.                 }
  203.             }
  204.         } //конец вложенного класса
  205.         Node tree; //ссылка на корень дерева
  206.                    //свойство позволяет получить доступ к значению информационного поля корня дерева
  207.  
  208.         public object Inf
  209.         {
  210.             set { tree.inf = value; }
  211.             get { return tree.inf; }
  212.         }
  213.         public BinaryTree() //открытый конструктор
  214.         {
  215.             tree = null;
  216.         }
  217.         private BinaryTree(Node r) //закрытый конструктор
  218.         {
  219.             tree = r;
  220.         }
  221.         public void Add(object nodeInf) //добавление узла в дерево
  222.         {
  223.             Node.Add(ref tree, nodeInf);
  224.         }
  225.         //организация различных способов обхода дерева
  226.         public void Preorder()
  227.         {
  228.             Node.Preorder(tree);
  229.         }
  230.         public void Inorder()
  231.         {
  232.             Node.Inorder(tree);
  233.         }
  234.         public void Postorder()
  235.         {
  236.             Node.Postorder(tree);
  237.         }
  238.  
  239.         //поиск ключевого узла в дереве
  240.         public BinaryTree Search(object key)
  241.         {
  242.             Node r;
  243.             Node.Search(tree, key, out r);
  244.             BinaryTree t = new BinaryTree(r);
  245.             return t;
  246.         }
  247.         //удаление ключевого узла в дереве
  248.         public void Delete(object key)
  249.         {
  250.             Node.Delete(ref tree, key);
  251.         }
  252.  
  253.         public double Check() // 1 деревья - подсчет среднего арифметического узлов, у которых есть два потомка
  254.         {
  255.             if (tree == null)
  256.                 return 0;
  257.  
  258.             int nodesCount = 0;
  259.             int totalSum = 0;
  260.  
  261.             void LeftRight(Node node)
  262.             {
  263.                 if (node.right != null && node.left == null)
  264.                 {
  265.                     LeftRight(node.right);
  266.                 }
  267.                 else if (node.left != null && node.right == null)
  268.                 {
  269.                     LeftRight(node.left);
  270.                 }
  271.                 else if (node.left != null && node.right != null)
  272.                 {
  273.                     nodesCount++;
  274.                     totalSum += (int)node.inf;
  275.                     //Console.WriteLine((int)node.inf + " " + nodesCount);
  276.                     LeftRight(node.left);
  277.                     LeftRight(node.right);
  278.                 }
  279.             }
  280.  
  281.             LeftRight(tree);
  282.  
  283.             return nodesCount == 0 ? 0 : (double)totalSum / nodesCount;
  284.         }
  285.        
  286.         public void PrintNodes(int lvl) // 2 деревья - подсчет количества узлов, не ниже lvl уровня (lvl и выше)
  287.         {
  288.             if (tree == null)
  289.             {
  290.                 Console.WriteLine("Дерево пусто");
  291.                 return;
  292.             }
  293.             int cnt = 0;
  294.             Node.PrintNodes(tree, 0, lvl, ref cnt);
  295.             Console.WriteLine($"Количество узлов не ниже {lvl}:" + " " + cnt);
  296.         }
  297.  
  298.         public bool Balance() //3 деревья - проверяем сбалансировано ли дерево
  299.         {
  300.             return Node.IsBalanced(tree);
  301.         }
  302.     }
  303. }
  304.  
  305.  
  306. //программка запуска
  307. using System;
  308. using System.Collections.Generic;
  309. using System.IO;
  310. using System.Linq;
  311. using System.Text;
  312. using System.Threading.Tasks;
  313.  
  314. namespace Myloyorrrr
  315. {
  316.     internal class Program
  317.     {
  318.         static void Main()
  319.         {
  320.             BinaryTree lipa = new BinaryTree();
  321.             int n = 0;
  322.  
  323.             // Чтение последовательности чисел из файла input.txt и добавление их в дерево
  324.             using (StreamReader f = new StreamReader("C:/Настя/книит/in.txt"))
  325.             {
  326.                 string line;
  327.                 while ((line = f.ReadLine()) != null)
  328.                 {
  329.                     string[] text = line.Split(' ');
  330.                     for (int i = 0; i < text.Length; i++)
  331.                     {
  332.                         int num = int.Parse(text[i]);
  333.                         lipa.Add(num);
  334.                         n++;
  335.                     }
  336.                 }
  337.  
  338.             }
  339.             //1 деревья
  340.             double average = lipa.Check();
  341.             Console.WriteLine("Среднее арифметическое значений узлов с двумя потомками: " + average);
  342.             Console.WriteLine();
  343.  
  344.             //2 деревья
  345.             Console.Write("Введите уровень: ");
  346.             int k = int.Parse(Console.ReadLine());
  347.             lipa.PrintNodes(k);
  348.             Console.WriteLine();
  349.  
  350.             // 3 деревья
  351.             bool IsBalance = lipa.Balance();
  352.             if (IsBalance)
  353.             {
  354.                 Console.WriteLine("Дерево является сбалансированным");
  355.             }
  356.             else
  357.             {
  358.                 Console.WriteLine("Дерево не является сбалансированным");
  359.             }
  360.         }
  361.     }
  362. }
  363.  
  364.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement