System.util.collections.OrderedTree.Delete C# (CSharp) Method

Delete() private method

private Delete ( OrderedTreeNode z ) : void
z OrderedTreeNode
return void
        private void Delete(OrderedTreeNode z)
        {
            // A node to be deleted will be:
            // 1. a leaf with no children
            // 2. have one child
            // 3. have two children
            // If the deleted node is red, the red black properties still hold.
            // If the deleted node is black, the tree needs rebalancing

            OrderedTreeNode x = new OrderedTreeNode(); // work node to contain the replacement node
            OrderedTreeNode y; // work node

            // find the replacement node (the successor to x) - the node one with
            // at *most* one child.
            if(z.Left == sentinelNode || z.Right == sentinelNode)
                y = z; // node has sentinel as a child
            else {
                // z has two children, find replacement node which will
                // be the leftmost node greater than z
                y = z.Right; // traverse right subtree
                while(y.Left != sentinelNode) // to find next node in sequence
                    y = y.Left;
            }

            // at this point, y contains the replacement node. it's content will be copied
            // to the valules in the node to be deleted

            // x (y's only child) is the node that will be linked to y's old parent.
            if(y.Left != sentinelNode)
                x = y.Left;
            else
                x = y.Right;

            // replace x's parent with y's parent and
            // link x to proper subtree in parent
            // this removes y from the chain
            x.Parent = y.Parent;
            if(y.Parent != null)
                if(y == y.Parent.Left)
                    y.Parent.Left = x;
                else
                    y.Parent.Right = x;
            else
                rbTree = x; // make x the root node

            // copy the values from y (the replacement node) to the node being deleted.
            // note: this effectively deletes the node.
            if(y != z) {
                z.Key = y.Key;
                z.Data = y.Data;
            }

            if(y.Color == OrderedTreeNode.BLACK)
                RestoreAfterDelete(x);

            lastNodeFound = sentinelNode;
        }