public void Insert(int data) { RBTreeNode newNode; RBTreeNode y = null; RBTreeNode x; if (Root == null) // Empty tree { Root = new RBTreeNode(data, red: false); return; } newNode = new RBTreeNode(data); // Instantiate as Red node x = Root; // Traverse until y is a leaf in a location where x doesn’t violate // the tree’s ordering while (x != null) { y = x; if (newNode < x) { x = x.Left(); } else { x = x.Right(); } } // Make newNode child of y newNode.SetParent(y); if (newNode < y) { y.SetLeft(newNode); } else { y.SetRight(newNode); } RebalancePostInsertion(newNode); }
private void RotateLeft(RBTreeNode x) { /** * Make right subtree left subtree */ // setup x & y RBTreeNode y = x.Right(); x.SetRight(y.Left()); // if y has a left child, make x the parent of the left child of y. if (y.Left() != null) { y.Left().SetParent(x); } y.SetParent(x.Parent()); // if x has no parent, make y the root of the tree. if (x.Parent() == null) { Root = y; } // else if x is the left child of p, make y the left child of p. else if (x == x.Parent().Left()) { x.Parent().SetLeft(y); } // else make y the right child of p else { x.Parent().SetRight(y); } // make y the parent of x y.SetLeft(x); x.SetParent(y); }
private void RotateRight(RBTreeNode y) { /** * Make left subtree right subtree */ // setup x & y RBTreeNode x = y.Left(); y.SetLeft(x.Right()); // if x has a right child, make y the parent of the right child of x. if (x.Right() != null) { x.Right().SetParent(y); } x.SetParent(y.Parent()); // if y has no parent, make x the root of the tree. if (y.Parent() == null) { Root = x; } // else if y is the right child of its parent p, make x the right child of p. else if (y == y.Parent().Right()) { y.Parent().SetRight(x); } // else assign x as the left child of p. else { y.Parent().SetLeft(x); } // make x the parent of y. x.SetRight(y); y.SetParent(x); }
private void Transplant(RBTreeNode oldNode, RBTreeNode newNode) { // Replace oldNode with newNode RBTreeNode parent = oldNode.Parent(); if (parent == null) { Root = newNode; } else if (oldNode == parent.Left()) { parent.SetLeft(newNode); } else { parent.SetRight(newNode); } // Null check for when newNode is null if (newNode != null) { newNode.SetParent(parent); } }