Example #1
0
        /// <summary>Removes one occurrence of a specific element from the <see cref="AVLTree{T}" />. <code>Complexity: O(LogN)</code></summary>
        /// <param name="value">The element to remove from the <see cref="AVLTree{T}"/>.</param>
        /// <returns><c>true</c> if the element was successfully removed from the <see cref="AVLTree{T}"/>; <c>false</c> otherwise.</returns>
        public override bool Remove(T value)
        {
            bool ret = true;

            AVLTreeNode <T> RemoveHelper(AVLTreeNode <T> node)
            {
                if (node == null)
                {
                    ret = false;
                    return(null);
                }

                int  comparison  = Compare(value, node.Value);
                bool decremented = false;

                if (comparison < 0)
                {
                    node.LeftChildren--;
                    decremented = true;
                    node.Left   = RemoveHelper(node.Left);
                }
                else if (comparison > 0)
                {
                    node.Right = RemoveHelper(node.Right);
                }
                else
                {
                    if (node.Left == null)
                    {
                        return(node.Right);
                    }

                    if (node.Right == null)
                    {
                        return(node.Left);
                    }

                    node.Value = AVLTreeNode <T> .RemoveInOrderSuccessor(ref node.Right);
                }

                if (ret)
                {
                    node.UpdateHeight();
                    node = node.PerformRotations();
                }
                else if (decremented)
                {
                    node.LeftChildren++;
                }

                return(node);
            }

            _root = RemoveHelper(_root);

            if (ret)
            {
                Count--;
            }
            return(ret);
        }