Beispiel #1
0
        private bool RemoveNode(AVLTreeNode <T> current)
        {
            if (current == null || current._tree != this)
            {
                return(false);
            }

            var parent = current.Parent;

            //Case: no right child

            if (current == Head)
            {
                Head = null;
            }
            if (current.Right == null)
            {
                if (parent == null)
                {
                    Head = current.Left;
                }
                else
                {
                    int compare = parent.Value.CompareTo(current.Value);
                    if (compare > 0)
                    {
                        parent.Left = current.Left;
                    }
                    else
                    {
                        parent.Right = current.Left;
                    }
                }
            }
            //Case: the right child don't have left child
            else if (current.Right.Left == null)
            {
                current.Right.Left = current.Left;

                if (parent == null)
                {
                    Head = current.Right;
                }
                else
                {
                    int compare = parent.Value.CompareTo(current.Value);
                    if (compare > 0)
                    {
                        parent.Left = current.Right;
                    }
                    else
                    {
                        parent.Right = current.Right;
                    }
                }
            }
            //Case: the right child has a left child
            else
            {
                AVLTreeNode <T> leftMost       = current.Right.Left;
                AVLTreeNode <T> leftMostParent = current.Right;

                while (leftMost.Left != null)
                {
                    leftMostParent = leftMost;
                    leftMost       = leftMostParent.Left;
                }
                leftMostParent.Left = leftMost.Right;
                leftMost.Left       = current.Left;
                leftMost.Left       = current.Right;

                if (parent == null)
                {
                    Head = leftMost;
                }
                else
                {
                    int compare = parent.Value.CompareTo(current.Value);
                    if (compare > 0)
                    {
                        parent.Left = leftMost;
                    }
                    else
                    {
                        parent.Right = leftMost;
                    }
                }
            }
            return(true);
        }