Advertisement
myloyo

деревья 3

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