public virtual TValue GetNearest <T>(T key) { IRedBlackLeaf <TKey, TValue> leaf = Root; IRedBlackLeaf <TKey, TValue> last = null; var compareKey = (TKey)Convert.ChangeType(key, typeof(TKey)); var compare = CreateLeaf(compareKey, default(TValue)); while (leaf != null) { if (leaf.GreaterThan(compare)) { leaf = leaf.Left; } else if (leaf.LessThan(compare)) { last = leaf; leaf = leaf.Right; } else { return(leaf.Value); } } if (last.IsEmpty()) { return(GetMaxLeaf().Value); } else { return(last.Value); } }
public virtual IRedBlackLeaf <TKey, TValue> Remove(IRedBlackLeaf <TKey, TValue> root, TKey key, ref bool done) { if (root.IsEmpty()) { done = true; } else { bool direction; if (root.Key.Equals(key)) { if (root.Left.IsEmpty() || root.Right.IsEmpty()) { var save = root[root.Left.IsEmpty()]; if (root.IsRed()) { done = true; } else if (save.IsRed()) { save.Color = LeafColor.BLACK; done = true; } return(save); } else { var heir = root.Left; while (!heir.Right.IsEmpty()) { heir = heir.Right; } root.Value = heir.Value; root.Key = heir.Key; key = heir.Key; } } direction = root.LessThan(CreateLeaf(key, default(TValue))); root[direction] = Remove(root[direction], key, ref done); if (!done) { root = BalancePostDelete(root, direction, ref done); } } return(root); }
public virtual TValue Get(TKey key) { Lock.EnterReadLock(); IRedBlackLeaf <TKey, TValue> leaf = Root; var compare = CreateLeaf(key, default(TValue)); while (leaf != null) { if (leaf.GreaterThan(compare)) { leaf = leaf.Left; } else if (leaf.LessThan(compare)) { leaf = leaf.Right; } else { break; } } Lock.ExitReadLock(); return(leaf.IsEmpty() ? default(TValue) : leaf.Value); }