Пример #1
0
        private AvlTreeNode <T> Balance()
        {
            FixHeight();
            var balanceFactor = BalanceFactor();

            if (balanceFactor == 2)
            {
                if (Right !.BalanceFactor() < 0)
                {
                    Right = Right.RotateRight();
                }

                return(RotateLeft());
            }

            if (balanceFactor == -2)
            {
                if (Left !.BalanceFactor() > 0)
                {
                    Left = Left.RotateLeft();
                }

                return(RotateRight());
            }

            return(this);
        }
Пример #2
0
        internal static AvlTreeNode <T>?Remove(AvlTreeNode <T>?root, T key, IComparer <T> comparer, int deep)
        {
            if (root == null)
            {
                return(null);
            }
            if (comparer.Compare(key, root.Value) < 0)
            {
                root.Left = Remove(root.Left, key, comparer, deep + 1);
            }
            else if (comparer.Compare(key, root.Value) > 0)
            {
                root.Right = Remove(root.Right, key, comparer, deep + 1);
            }
            else
            {
                var beforeLeft  = root.Left;
                var beforeRight = root.Right;
                if (beforeRight == null)
                {
                    return(beforeLeft);
                }
                var min = beforeRight.Min();
                min.Right = beforeRight.RemoveMin();
                min.Left  = beforeLeft;
                return(min.Balance());
            }

            return(root.Balance());
        }
Пример #3
0
        internal static AvlTreeNode <T> Add(AvlTreeNode <T>?root, T key, IComparer <T> comparer)
        {
            if (root == null)
            {
                return(new AvlTreeNode <T>(key));
            }
            var compare = comparer.Compare(key, root.Value);

            if (compare < 0)
            {
                root.Left = Add(root.Left, key, comparer);
            }
            else if (compare > 0)
            {
                root.Right = Add(root.Right, key, comparer);
            }
            else
            {
                throw new InvalidOperationException("Key exists");
            }
            return(root.Balance());
        }
 public void Remove(T key)
 {
     Root = AvlTreeNode <T> .Remove(Root, key, Comparer, 0);
 }
 public void Add(T key)
 {
     Root = AvlTreeNode <T> .Add(Root, key, Comparer);
 }