10.07.2015 Views

Generic Red-Black Tree and its C# Implementation - The Journal of ...

Generic Red-Black Tree and its C# Implementation - The Journal of ...

Generic Red-Black Tree and its C# Implementation - The Journal of ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

}return newNode;} else if (item.CompareTo(node.Item) < 0) {node.Left = InsertNode(node.Left, item, node);return node;} else if (item.CompareTo(node.Item) > 0) {node.Right = InsertNode(node.Right, item, node);return node;} else {throw new InvalidOperationException("Cannot add duplicate object.");}private void GetNodesAbove(Node curNode, out Node parent,out Node gr<strong>and</strong>Parent,out Node greatGr<strong>and</strong>Parent) {parent = null;gr<strong>and</strong>Parent = null;greatGr<strong>and</strong>Parent = null;if (curNode != null) {parent = curNode.Parent;}if (parent != null) {gr<strong>and</strong>Parent = parent.Parent;}if (gr<strong>and</strong>Parent != null) {greatGr<strong>and</strong>Parent = gr<strong>and</strong>Parent.Parent;}}private void Fix<strong>Tree</strong>AfterInsertion(Node child, Node parent,Node gr<strong>and</strong>Parent,Node greatGr<strong>and</strong>Parent) {if (gr<strong>and</strong>Parent != null) {Node uncle = (gr<strong>and</strong>Parent.Right == parent) ?gr<strong>and</strong>Parent.Left : gr<strong>and</strong>Parent.Right;if (uncle != null && parent.<strong>Red</strong> && uncle.<strong>Red</strong>) {uncle.<strong>Red</strong> = false;parent.<strong>Red</strong> = false;gr<strong>and</strong>Parent.<strong>Red</strong> = true;Node higher = null;Node stillHigher = null;if (greatGr<strong>and</strong>Parent != null) {higher = greatGr<strong>and</strong>Parent.Parent;}if (higher != null) {stillHigher = higher.Parent;}Fix<strong>Tree</strong>AfterInsertion(gr<strong>and</strong>Parent, greatGr<strong>and</strong>Parent,higher, stillHigher);} else if (uncle == null || parent.<strong>Red</strong> && !uncle.<strong>Red</strong>) {if (gr<strong>and</strong>Parent.Right == parent &&parent.Right == child) { // right-right caseparent.<strong>Red</strong> = false;gr<strong>and</strong>Parent.<strong>Red</strong> = true;if (greatGr<strong>and</strong>Parent != null) {if (greatGr<strong>and</strong>Parent.Right == gr<strong>and</strong>Parent) {LeftRotate(ref gr<strong>and</strong>Parent);greatGr<strong>and</strong>Parent.Right = gr<strong>and</strong>Parent;} else {LeftRotate(ref gr<strong>and</strong>Parent);VOL. 4, NO. 2 JOURNAL OF OBJECT TECHNOLOGY 71

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!