Пример #1
0
 /// <summary>
 /// Insert the specified value into the tree. Runtime O(Log n)
 /// </summary>
 /// <param name="val">Value.</param>
 public void Insert(T val)
 {
     m_root = zInsert(m_root, val);
 }
Пример #2
0
        private AVLTreeNode <T> zDeleteNode(AVLTreeNode <T> node, T val)
        {
            if (node == null)
            {
                return(node);
            }

            if (val.CompareTo(node.Value) > 0)
            {
                node.Right = zDeleteNode(node.Right, val);
            }
            else if (val.CompareTo(node.Value) < 0)
            {
                node.Left = zDeleteNode(node.Left, val);
            }
            else
            {
                //node with  only one or no child
                if (node.Left == null || node.Right == null)
                {
                    AVLTreeNode <T> temp = null;

                    if (node.Left != null)
                    {
                        temp = node.Left;
                    }
                    else if (node.Right != null)
                    {
                        temp = node.Right;
                    }

                    node = temp;
                }
                else
                {
                    //node with two children
                    var min = zFindMin(node.Right);
                    node.Value = min.Value;

                    //delete min since it replaced this node
                    node.Right = zDeleteNode(node.Right, min.Value);
                }
            }

            //if node is null return
            if (node == null)
            {
                return(node);
            }

            //update height of ancestor
            node.Height = 1 + Math.Max(Height(node.Left), Height(node.Right));

            //get balance factor
            int balance = zGetBalanceFactor(node);

            //if unbalanced then there are 4 cases to handle
            if (balance > 1 && zGetBalanceFactor(node.Left) >= 0) //left left
            {
                return(RightRotate(node));
            }

            if (balance > 1 && zGetBalanceFactor(node.Left) < 0) //right right
            {
                node.Left = LeftRotate(node.Left);
                return(RightRotate(node));
            }

            if (balance < -1 && zGetBalanceFactor(node.Right) <= 0) //left right
            {
                return(LeftRotate(node));
            }

            if (balance < -1 && zGetBalanceFactor(node.Right) > 0)
            {
                node.Right = RightRotate(node.Right);
                return(LeftRotate(node));
            }

            return(node);
        }
Пример #3
0
 public AVLTree(T val)
 {
     m_root = new AVLTreeNode <T>(val);
 }
Пример #4
0
 /// <summary>
 /// Delete the specified node in the tree. Runtime O(log n)
 /// </summary>
 /// <param name="val">Value.</param>
 public void Delete(T val)
 {
     m_root = zDeleteNode(m_root, val);
 }