So now that we know the main characteristics of red-black trees, let's see how to implement the base class.
Then, we will progress to the insertion scenario, which is a little bit more complex than in the binary search tree case, because this time we have to maintain the five color conditions after the insertion of a new node in the tree.
Let's see the first version of the RedBlackTreeNode
class and the RedBlackTreeColor
enumeration that will help us with the color.
In Xcode, go to File | New | Playground, and call it B05101_6_RedBlackTree
. In the Sources
folder, add a new file called RedBlackTreeNode.swift
. Add the following code inside it:
//Enumeration to model the possible colors of a node public enum RedBlackTreeColor : Int { case red = 0 case black = 1 } public class RedBlackTreeNode<T:Comparable> { //Value and children-parent vars public var value:T public var leftChild...