Esempio n. 1
0
        /// <summary>
        /// Removes the specified key from the current instance of the scapegoat tree. Rebuilds tree if it's unbalanced.
        /// </summary>
        /// <param name="key">Key value.</param>
        /// <returns>True - if key was successfully removed, false - if the key wasn't found in the tree.</returns>
        public bool Delete(TKey key)
        {
            if (Root == null)
            {
                return(false);
            }

            if (Remove(Root, Root, key))
            {
                Size--;

                if (Root != null && Size < Alpha * MaxSize)
                {
                    TreeIsUnbalanced?.Invoke(this, EventArgs.Empty);

                    var list = new List <Node <TKey> >();

                    Extensions.FlattenTree(Root, list);

                    Root = Extensions.RebuildFromList(list, 0, list.Count - 1);

                    MaxSize = Size;
                }

                return(true);
            }

            return(false);
        }
Esempio n. 2
0
        /// <summary>
        /// Inserts a new key into current instance of the scapegoat tree. Rebuilds tree if it's unbalanced.
        /// </summary>
        /// <param name="key">Key value.</param>
        /// <returns>True - if insertion is successful, false - if the key is already present in the tree.</returns>
        public bool Insert(TKey key)
        {
            var node = new Node <TKey>(key);

            if (Root == null)
            {
                Root = node;

                UpdateSizes();

                return(true);
            }

            var path = new Stack <Node <TKey> >();

            var current = Root;

            var found = false;

            while (!found)
            {
                path.Push(current);

                var result = current.Key.CompareTo(node.Key);

                switch (result)
                {
                case < 0 when current.Right != null:
                    current = current.Right;
                    continue;

                case < 0:
                    current.Right = node;
                    found         = true;
                    break;

                case > 0 when current.Left != null:
                    current = current.Left;
                    continue;

                case > 0:
                    current.Left = node;
                    found        = true;
                    break;

                default:
                    return(false);
                }
            }

            UpdateSizes();

            if (path.Count > Root.GetAlphaHeight(Alpha))
            {
                TreeIsUnbalanced?.Invoke(this, EventArgs.Empty);

                BalanceFromPath(path);

                MaxSize = Math.Max(MaxSize, Size);
            }

            return(true);
        }