// Private method that converts each node to a node in a RBTree private void Convert(Node node, RBTree <T> tree) { if (node == null) { return; } Node copy = CopyNonDeleted(node); // Case 2-node: create a black node // Case 3-node: create a black node (with larger value) as parent and red child // Case 4-node: create a black node (with middle value) as parent and two red children if (copy.NumItems == 1) { tree.Add(copy.Items[0], RBTree <T> .Color.BLACK); } else if (copy.NumItems == 2) { tree.Add(copy.Items[1], RBTree <T> .Color.BLACK); tree.Add(copy.Items[0], RBTree <T> .Color.RED); } else if (copy.NumItems == 3) { tree.Add(copy.Items[1], RBTree <T> .Color.BLACK); tree.Add(copy.Items[0], RBTree <T> .Color.RED); tree.Add(copy.Items[2], RBTree <T> .Color.RED); } // Run Convert for all children of a node // Note that piece of sh- code also works for the root, as it only has one child for (int i = 0; i < node.NumItems + 1; i++) { Convert(node.Children[i], tree); } }
// Returns an instance of RBTree (red-black tree) that is an isometry of the current tree public RBTree <T> Convert() { RBTree <T> tree = new RBTree <T>(); Convert(root, tree); return(tree); }
private static void RunTests(int numTests) { while (numTests > 0) { numTests--; Tree <int> tree = new Tree <int>(); List <int> list = new List <int>(); // Test delete without any items tree.Delete(rand.Next()); // Insert 20 values into the tree (note that duplicate values are not inserted) for (int i = 0; i < 20; i++) { int item = -1; while (item < 0 || list.Contains(item)) { item = rand.Next(100) + 1; } tree.Insert(item); list.Add(item); } for (int i = 0; i < list.Count; i++) { Console.Write("{0} ", list[i]); } Console.WriteLine(); // Test printing tree.Print(); // Test converting to Red-Black tree RBTree <int> rbtree = tree.Convert(); rbtree.Print(); // Randomize for delete testing list = Randomize <int>(list); // Check if all items are in for (int i = 0; i < list.Count; i++) { if (!tree.Contains(list[i])) { Console.WriteLine("Something horrible happened here."); } } // Test delete for (int i = 0; i < list.Count; i++) { tree.Delete(list[i]); } // Output the number of items Console.WriteLine("The item count is (should be 0): {0}", tree.Size()); // Test inserting them back for (int i = 0; i < list.Count; i++) { tree.Insert(list[i]); } // Output the number of items Console.WriteLine("The item count is (should be {0}): {1}", list.Count, tree.Size()); Console.WriteLine(); } }