public RedBlackLeaf(TKey key, TValue value, RedBlackLeaf <TKey, TValue> parent) { Parent = parent; Key = key; Value = value; Color = LeafColor.RED; Comparer = new Comparer(CultureInfo.InvariantCulture); }
public override IRedBlackLeaf <TKey, TValue> Insert(IRedBlackLeaf <TKey, TValue> root, IRedBlackLeaf <TKey, TValue> leaf) { if (Root.IsEmpty()) { Root = leaf; } else { IRedBlackLeaf <TKey, TValue> g, t, p, q, head; head = new RedBlackLeaf <TKey, TValue>(default(TKey), default(TValue), null); g = t = q = p = null; bool direction, last; direction = last = false; t = head; q = t.Right = Root; for ( ;;) { if (q.IsEmpty()) { p[direction] = q = leaf; if (q.IsEmpty()) { return(Root); } } else if (q.Left.IsRed() && q.Right.IsRed()) { q.Color = LeafColor.RED; q.Left.Color = LeafColor.BLACK; q.Right.Color = LeafColor.BLACK; } if (q.IsRed() && p.IsRed()) { var newDirection = t.Right.Key.Equals(g.Key); var lastIteration = p[last]; var lastIterationKey = lastIteration == null ? default(TKey) : lastIteration.Key; if (q.Key.Equals(lastIterationKey)) { t[newDirection] = Rotate(g, !last); } else { t[newDirection] = DoubleRotate(g, !last); } } if (q.Key.Equals(leaf.Key)) { break; } last = direction; direction = q.LessThan(leaf); if (!g.IsEmpty()) { t = g; } g = p; p = q; q = q[direction]; } Root = head.Right; } Root.Color = LeafColor.BLACK; return(Root); }