Пример #1
0
        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);
            }
        }
Пример #2
0
        protected virtual IAvlLeaf <TKey, TValue> Insert(IAvlLeaf <TKey, TValue> root, IAvlLeaf <TKey, TValue> leaf,
                                                         ref bool done)
        {
            if (root.IsEmpty())
            {
                root = leaf;
            }
            else
            {
                leaf.Parent = root;
                var direction = leaf.GreaterThan(root.Key);
                root[direction] = Insert(root[direction], leaf, ref done);

                if (!done)
                {
                    root.Balance += direction ? 1 : -1;
                    if (root.Balance == 0)
                    {
                        done = true;
                    }
                    else if (Math.Abs(root.Balance) > 1)
                    {
                        root = BalancePostInsert(root, direction);
                        done = true;
                    }
                }
            }
            return(root);
        }