Exemplo n.º 1
0
        /// <summary>Returns all sub-trees enumerated from left to right.</summary>
        /// <returns>Enumerated sub-trees or empty if tree is empty.</returns>
        public IEnumerable <ImMap <V> > Enumerate()
        {
            if (Height == 0)
            {
                yield break;
            }

            var parents = new ImMap <V> [Height];

            var node        = this;
            var parentCount = -1;

            while (node.Height != 0 || parentCount != -1)
            {
                if (node.Height != 0)
                {
                    parents[++parentCount] = node;
                    node = node.Left;
                }
                else
                {
                    node = parents[parentCount--];
                    yield return(node);

                    node = node.Right;
                }
            }
        }
Exemplo n.º 2
0
 private ImMap(int key, V value, ImMap <V> left, ImMap <V> right, int height)
 {
     Key    = key;
     Value  = value;
     Left   = left;
     Right  = right;
     Height = height;
 }
Exemplo n.º 3
0
 private ImMap(int key, V value, ImMap <V> left, ImMap <V> right)
 {
     Key    = key;
     Value  = value;
     Left   = left;
     Right  = right;
     Height = 1 + (left.Height > right.Height ? left.Height : right.Height);
 }
Exemplo n.º 4
0
 private ImMap(int key, V value)
 {
     Key    = key;
     Value  = value;
     Left   = Empty;
     Right  = Empty;
     Height = 1;
 }
Exemplo n.º 5
0
        private ImMap <V> RemoveImpl(int key, bool ignoreKey = false)
        {
            if (Height == 0)
            {
                return(this);
            }

            ImMap <V> result;

            if (key == Key || ignoreKey) // found node
            {
                if (Height == 1)         // remove node
                {
                    return(Empty);
                }

                if (Right.IsEmpty)
                {
                    result = Left;
                }
                else if (Left.IsEmpty)
                {
                    result = Right;
                }
                else
                {
                    // we have two children, so remove the next highest node and replace this node with it.
                    var successor = Right;
                    while (!successor.Left.IsEmpty)
                    {
                        successor = successor.Left;
                    }
                    result = new ImMap <V>(successor.Key, successor.Value,
                                           Left, Right.RemoveImpl(successor.Key, ignoreKey: true));
                }
            }
            else if (key < Key)
            {
                result = new ImMap <V>(Key, Value, Left.RemoveImpl(key), Right);
            }
            else
            {
                result = new ImMap <V>(Key, Value, Left, Right.RemoveImpl(key));
            }

            return(result.KeepBalance());
        }