public virtual TValue GetNearest <T>(T key) { IAvlLeaf <TKey, TValue> leaf = Root; IAvlLeaf <TKey, TValue> last = null; var compareKey = (TKey)Convert.ChangeType(key, typeof(TKey)); while (leaf != null) { if (leaf.GreaterThan(compareKey)) { leaf = leaf.Left; } else if (leaf.LessThan(compareKey)) { last = leaf; leaf = leaf.Right; } else { return(leaf.Value); } } if (last.IsEmpty()) { return(GetMaxLeaf().Value); } else { return(last.Value); } }
protected virtual IAvlLeaf <TKey, TValue> Remove(IAvlLeaf <TKey, TValue> root, TKey key, ref bool done) { if (!root.IsEmpty()) { bool direction = false; if (root.Key.Equals(key)) { if (root.Left.IsEmpty() || root.Right.IsEmpty()) { direction = root.Left.IsEmpty(); var worker = root[direction]; return(worker); } else { var worker = root.Left; while (!worker.Right.IsEmpty()) { worker = worker.Right; } root.Key = worker.Key; key = worker.Key; } } direction = root.LessThan(key); root[direction] = Remove(root[direction], key, ref done); if (!done) { root.Balance += direction ? -1 : 1; if (Math.Abs(root.Balance) == 1) { done = true; } else if (Math.Abs(root.Balance) > 1) { root = BalancePostDelete(root, direction, ref done); } } } return(root); }