Example #1
0
        public void InsertNode(int value)
        {
            RedBlackNode newNode = new RedBlackNode();

            newNode.key = value;
            newNode.SetColor("red");
            RedBlackNode current = root;
            RedBlackNode parent  = current;

            bool done = false;

            if (!rootSet)
            {
                root.key = value;
                root.SetColor("black");
                rootSet = true;
            }
            else
            {
                while (!done)
                {
                    parent = current;

                    if (value < current.key)
                    {
                        current = current.leftChild;
                        if (current == null)
                        {
                            parent.leftChild = newNode;
                            newNode.parent   = parent;
                            done             = true;
                            Rebalance(newNode);
                        }
                    }
                    else if (value > current.key)
                    {
                        current = current.rightChild;
                        if (current == null)
                        {
                            parent.rightChild = newNode;
                            newNode.parent    = parent;
                            done = true;
                            Rebalance(newNode);
                        }
                    }
                }
            }
        }
Example #2
0
        private void RightRotation(RedBlackNode node)
        {
            RedBlackNode newParent = node.leftChild;      // new parent = grandparent's left child

            newParent.leftChild.parent     = newParent;   // problem child's parent = new parent
            newParent.parent               = node.parent; // new parents parent = grandparent's parent
            newParent.rightChild           = node;        //  new parent's left child = grandparent
            newParent.rightChild.parent    = newParent;
            newParent.rightChild.leftChild = null;
            if (newParent.parent != null)
            {
                if (newParent.parent.key < newParent.key)
                {
                    newParent.parent.rightChild = newParent;
                }
                else if (newParent.parent.key > newParent.key)
                {
                    newParent.parent.leftChild = newParent;
                }
            }
            else if (newParent.parent == null)
            {
                newParent.parent = null;
                root             = newParent;
            }

            newParent.SetColor("Black");
            node.SetColor("Red");
        }