Exemplo n.º 1
0
        private TreapNode InsertNode(TreapNode node, TreapNode tree)
        {
            //if treap is empty
            if (tree == null)
            {
                return(node);
            }

            int result = _comparer.Compare(node.Key, tree.Key);

            //"Plant" tree in the left node
            if (result < 0)
            {
                tree.Left = InsertNode(node, tree.Left);

                //rebalance tree in order to get the lowest priority on top
                if (tree.Left.Priority < tree.Priority)
                {
                    tree = tree.RotateRight();
                }
            }
            else if (result > 0)
            {
                tree.Right = InsertNode(node, tree.Right);

                if (tree.Right.Priority < tree.Priority)
                {
                    tree = tree.RotateLeft();
                }
            }
            else //key is found
            {
                tree.Data.Value = node.Data.Value;
                _updateCount    = false;
            }
            return(tree);
        }