Beispiel #1
0
        //reorder the tree node so that heap property is valid
        private void heapify(TreapTreeNode <T> node)
        {
            while (node.Parent != null)
            {
                node.UpdateCounts();
                if (node.Priority < node.Parent.Priority)
                {
                    node = node.IsLeftChild ? rightRotate(node.Parent) : leftRotate(node.Parent);
                }
                else
                {
                    break;
                }
            }

            node.UpdateCounts(true);
        }
Beispiel #2
0
        private void delete(TreapTreeNode <T> node, T value)
        {
            while (true)
            {
                if (node != null)
                {
                    var compareResult = comparer.Compare(node.Value, value);

                    //node is less than the search value so move right to find the deletion node
                    if (compareResult < 0)
                    {
                        node = node.Right ?? throw new Exception("Item do not exist");
                        continue;
                    }
                    //node is less than the search value so move left to find the deletion node

                    if (compareResult > 0)
                    {
                        node = node.Left ?? throw new Exception("Item do not exist");
                        continue;
                    }
                }

                //node is a leaf node
                if (node != null && node.IsLeaf)
                {
                    deleteLeaf(node);
                }
                else
                {
                    //case one - right tree is null (move sub tree up)
                    if (node?.Left != null && node.Right == null)
                    {
                        deleteLeftNode(node);
                    }
                    //case two - left tree is null  (move sub tree up)
                    else if (node?.Right != null && node.Left == null)
                    {
                        deleteRightNode(node);
                    }
                    //case three - two child trees
                    //replace the node value with maximum element of left subtree (left max node)
                    //and then delete the left max node
                    else
                    {
                        if (node != null)
                        {
                            var maxLeftNode = findMax(node.Left);

                            node.Value = maxLeftNode.Value;

                            //delete left max node
                            node  = node.Left;
                            value = maxLeftNode.Value;
                        }

                        continue;
                    }
                }

                break;
            }

            node.UpdateCounts(true);
        }