// Basic Insert function - Uses polymorphism public void Insert(RBNode node, RBTree tree) { node = (RBNode)base.Insert(node, tree); if (node == null) { return; } // Add the NilNodes as leaves node.LChild = NilNode; node.RChild = NilNode; // If we are inserting the root, make it black, otherwise, make it red if (node.Parent == null) { node.Parent = NilNode; node.NodeColor = COLOR.BLACK; } else { node.NodeColor = COLOR.RED; } // Fix-Up FixUpRB(tree, node); }
// Fix nodes public void FixUpRB(RBTree tree, RBNode N) { while (parent(N).NodeColor == COLOR.RED) { // If parent(N) is an LChild of grandparent(N) if (parent(N) == grandparent(N).LChild) { // Y is the uncle of Node N RBNode Y = (RBNode)grandparent(N).RChild; // Case 1: RED Uncle, if (Y.NodeColor == COLOR.RED) { // Make the parent and uncle black parent(N).NodeColor = COLOR.BLACK; Y.NodeColor = COLOR.BLACK; grandparent(N).NodeColor = COLOR.RED; N = grandparent(N); } // Case 2: BLACK Uncle else { if (N == parent(N).RChild) { N = parent(N); LeftRotate(N); } parent(N).NodeColor = COLOR.BLACK; grandparent(N).NodeColor = COLOR.RED; RightRotate(grandparent(N)); } } else { // Y is the uncle of Node N RBNode Y = (RBNode)grandparent(N).LChild; // Case 1: RED Uncle, if (Y.NodeColor == COLOR.RED) { // Make the parent and uncle black parent(N).NodeColor = COLOR.BLACK; Y.NodeColor = COLOR.BLACK; grandparent(N).NodeColor = COLOR.RED; N = grandparent(N); } // Case 2: BLACK Uncle else { if (N == parent(N).LChild) { N = parent(N); RightRotate(N); } parent(N).NodeColor = COLOR.BLACK; grandparent(N).NodeColor = COLOR.RED; LeftRotate(grandparent(N)); } } } // Color it black ((RBNode)tree.root).NodeColor = COLOR.BLACK; }