Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Балансировка бинарного дерева при добавлении в него узла");
            Console.ResetColor();
            Console.Write("Введите значение верхнего узла: ");
            int n = InputNumber();
            IdealBalanceBinaryThree <int> three = new IdealBalanceBinaryThree <int>(n);

            Console.Write("Сколько элементов добавить в дерево: ");
            int q = InputNumber();

            for (int i = 0; i < q; i++)
            {
                three.Add(i);
            }
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Печать дерева:");
            Console.ResetColor();
            IdealBalanceBinaryThree <int> .ShowTree(three);

            Console.WriteLine("Количество элементов в дереве: {0}", three.Count);
            Console.WriteLine($"Количество элементов в правом поддереве: {three.SeachCountForRight(three)}");
            Console.WriteLine($"Количество элементов в правом поддереве: {three.SeachCountForLeft(three)}");
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Доп.функция - высота дерева равна: {0}", three.SearchHeight(three));
            Console.ResetColor();
            Console.ReadLine();
        }
        public IdealBalanceBinaryThree <T> Add(T item)
        {
            IdealBalanceBinaryThree <T> begin = this;
            IdealBalanceBinaryThree <T> temp  = begin;

            if (begin.right == null && begin.left == null)
            {
                begin.right = new IdealBalanceBinaryThree <T>(item);
                return(begin);
            }
            if (begin.right == null && begin.left != null)
            {
                begin.right = new IdealBalanceBinaryThree <T>(item);
                return(begin);
            }
            if (begin.right != null && begin.left == null)
            {
                begin.left = new IdealBalanceBinaryThree <T>(item);
                return(begin);
            }
            if (begin.right != null && begin.left != null)
            {
                if (begin.SeachCountForRight(begin) == begin.SeachCountForLeft(begin))
                {
                    temp = begin.right;
                    temp.Add(item);
                    return(begin);
                }
                if (begin.SeachCountForRight(begin) > begin.SeachCountForLeft(begin))
                {
                    temp = begin.left;
                    temp.Add(item);
                    return(begin);
                }
                if (begin.SeachCountForRight(begin) < begin.SeachCountForLeft(begin))
                {
                    temp = begin.right;
                    temp.Add(item);
                    return(begin);
                }
            }
            return(begin);
        }