예제 #1
0
        public T Max()
        {
            if (root == null)
            {
                throw new Exception("The tree is empty!");
            }

            AvlNode pos = root;

            while (pos.Right != null)
            {
                pos = pos.Right;
            }

            return(pos.Value);
        }
예제 #2
0
 internal AvlNode <T> Insert(AvlNode <T> node, T value)
 {
     if (node == null)
     {
         return(new AvlNode <T>(value));
     }
     if (Compare(node.Value, value) > 0)
     {
         node.Left = Insert((AvlNode <T>)node.Left, value);
     }
     else
     {
         node.Right = Insert((AvlNode <T>)node.Right, value);
     }
     return(Balance(node));
 }
예제 #3
0
        /// <summary>
        /// Removes a node that has no children.
        /// </summary>
        /// <param name="node">The node.</param>
        protected override void RemoveNodeWithNoChild(BinarySearchTree <TKey, TValue> .Node node)
        {
            if (node == null)
            {
                return;
            }

            AvlNode parent = node.Parent as AvlNode;

            base.RemoveNodeWithNoChild(node);

            if (parent != null)
            {
                this.Balance(parent);
            }
        }
예제 #4
0
        private static AvlNode RotateRight(AvlNode y)
        {
            var x    = y.Left;
            var temp = x.Right;

            // rotation
            x.Right = y;
            y.Left  = temp;

            // update height
            y.Height = Math.Max(Height(y.Left), Height(y.Right)) + 1;
            x.Height = Math.Max(Height(x.Left), Height(x.Right)) + 1;

            // new root
            return(x);
        }
예제 #5
0
        private static AvlNode RotateLeft(AvlNode x)
        {
            var y    = x.Right;
            var temp = y.Left;

            // rotation
            y.Left  = x;
            x.Right = temp;

            // update height
            x.Height = Math.Max(Height(x.Left), Height(x.Right)) + 1;
            y.Height = Math.Max(Height(y.Left), Height(y.Right)) + 1;

            // new root
            return(y);
        }
예제 #6
0
        public TValue Pop()
        {
            if (_root == null)
            {
                return(default(TValue));
            }

            AvlNode currentNode = _root;

            while (currentNode.Left != null)
            {
                currentNode = currentNode.Left;
            }

            return(Delete(currentNode.Key, currentNode.Value));
        }
예제 #7
0
        private void InsertBalance(AvlNode node, int balance)
        {
            while (node != null)
            {
                balance = (node.Balance += balance);

                if (balance == 0)
                {
                    return;
                }
                else if (balance == 2)
                {
                    if (node.Left.Balance == 1)
                    {
                        RotateRight(node);
                    }
                    else
                    {
                        RotateLeftRight(node);
                    }

                    return;
                }
                else if (balance == -2)
                {
                    if (node.Right.Balance == -1)
                    {
                        RotateLeft(node);
                    }
                    else
                    {
                        RotateRightLeft(node);
                    }

                    return;
                }

                AvlNode parent = node.Parent;

                if (parent != null)
                {
                    balance = parent.Left == node ? 1 : -1;
                }

                node = parent;
            }
        }
예제 #8
0
            public AvlNode AddOrReplace([NotNull] TKey key, TValue value)
            {
                var compare = key.CompareTo(this.key);

                if (compare == 0)
                {
                    this.value = value;
                    return(this);
                }

                if (compare < 0)
                {
                    if (this.left != null)
                    {
                        this.left = this.left.AddOrReplace(key, value);

                        // Check whether rebalance is necessary and update height
                        var node = Rebalance(this);
                        node.height = CalculateHeight(node);
                        return(node);
                    }
                    else
                    {
                        this.left   = new AvlNode(key, value);
                        this.height = 2;
                        return(this);
                    }
                }
                else
                {
                    if (this.right != null)
                    {
                        this.right = this.right.AddOrReplace(key, value);

                        var node = Rebalance(this);
                        node.height = CalculateHeight(node);
                        return(node);
                    }
                    else
                    {
                        this.right  = new AvlNode(key, value);
                        this.height = 2;
                        return(this);
                    }
                }
            }
예제 #9
0
            public static int AssertBalanced(AvlNode V)
            {
                if (V == null)
                {
                    return(0);
                }

                int a = AssertBalanced(V.Left);
                int b = AssertBalanced(V.Right);

                if (((a - b) != V.Balance) || (Math.Abs(a - b) >= 2))
                {
                    throw new InvalidOperationException();
                }

                return(1 + Math.Max(a, b));
            }
예제 #10
0
            /// <summary>
            /// Inserts the specified segment to the tree.
            /// </summary>
            /// <param name="segment">The segment.</param>
            /// <exception cref="System.ArgumentNullException">The segment is null.</exception>
            public void Insert(SweepLineSegment segment)
            {
                if (segment == null)
                {
                    throw new ArgumentNullException(nameof(segment));
                }

                if (this.root == null)
                {
                    this.root = new AvlNode {
                        Key = segment, Value = segment, Balance = 0
                    };
                    this.currentNode = this.root;
                    this.nodeCount++;
                    this.version++;
                    return;
                }

                AvlNode node = this.SearchNodeForInsertion(segment) as AvlNode;

                if (node == null)
                {
                    return;
                }

                if (this.Comparer.Compare(segment, node.Key) < 0)
                {
                    node.LeftChild = new AvlNode {
                        Key = segment, Value = segment, Parent = node, Balance = 0
                    };
                    node.Balance     = -1;
                    this.currentNode = node.LeftChild;
                }
                else
                {
                    node.RightChild = new AvlNode {
                        Key = segment, Value = segment, Parent = node, Balance = 0
                    };
                    node.Balance     = 1;
                    this.currentNode = node.RightChild;
                }

                this.Balance(node);
                this.nodeCount++;
                this.version++;
            }
예제 #11
0
            /// <summary>
            /// Inserts the specified segment to the tree.
            /// </summary>
            /// <param name="segment">The segment.</param>
            /// <exception cref="System.ArgumentNullException">The segment is null.</exception>
            public void Insert(SweepLineSegment segment)
            {
                if (segment == null)
                {
                    throw new ArgumentNullException("segment", "The segment is null.");
                }

                if (_root == null)
                {
                    _root = new AvlNode {
                        Key = segment, Value = segment, Balance = 0
                    };
                    _currentNode = _root;
                    _nodeCount++;
                    _version++;
                    return;
                }

                AvlNode node = SearchNodeForInsertion(segment) as AvlNode;

                if (node == null)
                {
                    return;
                }

                if (_comparer.Compare(segment, node.Key) < 0)
                {
                    node.LeftChild = new AvlNode {
                        Key = segment, Value = segment, Parent = node, Balance = 0
                    };
                    node.Balance = -1;
                    _currentNode = node.LeftChild;
                }
                else
                {
                    node.RightChild = new AvlNode {
                        Key = segment, Value = segment, Parent = node, Balance = 0
                    };
                    node.Balance = 1;
                    _currentNode = node.RightChild;
                }

                Balance(node);
                _nodeCount++;
                _version++;
            }
예제 #12
0
        private static AvlNode FixWithRotateRight(AvlNode N)
        {
            var L  = N.Left;
            var LR = L.Right;

            switch (L.Balance)
            {
            case 1:
                N.Balance = 0;
                L.Balance = 0;
                N.Left    = LR;
                L.Right   = N;
                return(L);

            case 0:
                N.Balance = 1;
                L.Balance = -1;
                N.Left    = LR;
                L.Right   = N;
                return(L);

            case -1:
                L.Right = LR.Left;
                N.Left  = LR.Right;

                var nLRBalance = (sbyte)-LR.Balance;
                if (nLRBalance > 0)
                {
                    L.Balance = nLRBalance;
                    N.Balance = 0;
                }
                else
                {
                    L.Balance = 0;
                    N.Balance = nLRBalance;
                }

                LR.Balance = 0;
                LR.Left    = L;
                LR.Right   = N;

                return(LR);
            }

            return(null);
        }
예제 #13
0
        private static AvlNode FixWithRotateLeft(AvlNode N)
        {
            var R  = N.Right;
            var RL = R.Left;

            switch (R.Balance)
            {
            case -1:
                N.Balance = 0;
                R.Balance = 0;
                N.Right   = RL;
                R.Left    = N;
                return(R);

            case 0:
                N.Balance = -1;
                R.Balance = 1;
                N.Right   = RL;
                R.Left    = N;
                return(R);

            case 1:
                R.Left  = RL.Right;
                N.Right = RL.Left;

                var nRLBalance = (sbyte)-RL.Balance;
                if (nRLBalance > 0)
                {
                    R.Balance = 0;
                    N.Balance = nRLBalance;
                }
                else
                {
                    R.Balance = nRLBalance;
                    N.Balance = 0;
                }

                RL.Balance = 0;
                RL.Right   = R;
                RL.Left    = N;

                return(RL);
            }

            return(null);
        }
예제 #14
0
        // ******************************************************************
        public bool MoveNext()
        {
            if (!_convexHull.IsInitDone)
            {
                return(false);
            }

            if (_currentQuadrant == null)
            {
                _currentQuadrant = _convexHull._q1;
                _currentNode     = _currentQuadrant.GetFirstNode();
            }
            else
            {
                for (;;)
                {
                    AvlNode <PolygonPoint> nextNode = _currentNode.GetNextNode();
                    if (nextNode == null)
                    {
                        if (_currentQuadrant == _convexHull._q4)
                        {
                            return(false);
                        }

                        _currentQuadrant = _currentQuadrant.GetNextQuadrant();

                        nextNode = _currentQuadrant.GetFirstNode();

                        if (nextNode.Item == _currentNode.Item)
                        {
                            _currentNode = nextNode;
                            return(MoveNext());
                        }
                    }
                    else
                    {
                        _currentNode = nextNode;
                        break;
                    }
                }
            }

            return(true);
        }
예제 #15
0
        private static void Description <TKey>(StringBuilder builder, AvlNode <TKey, TKey> node)
        {
            if (node != null)
            {
                builder.Append(node.Key);

                for (int i = 0; i < node.Balance; i++)
                {
                    builder.Append("+");
                }

                for (int i = node.Balance; i < 0; i++)
                {
                    builder.Append("-");
                }

                if (node.Left != null || node.Right != null)
                {
                    builder.Append(":{");

                    if (node.Left == null)
                    {
                        builder.Append("~");
                    }
                    else
                    {
                        Description(builder, node.Left);
                    }

                    builder.Append(",");

                    if (node.Right == null)
                    {
                        builder.Append("~");
                    }
                    else
                    {
                        Description(builder, node.Right);
                    }

                    builder.Append("}");
                }
            }
        }
        public static int Count <TKey>(this AvlNode <TKey, TKey> source)
        {
            int count = 1;

            AvlNode <TKey, TKey> left  = source.Left;
            AvlNode <TKey, TKey> right = source.Right;

            if (right != null)
            {
                count += Count(left);
            }

            if (right != null)
            {
                count += Count(right);
            }

            return(count);
        }
예제 #17
0
파일: AvlTree.cs 프로젝트: taoxiease/roops
    private AvlNode findMax(final AvlNode arg)
    {
        AvlNode t = arg;

        if (t == null)
        {
            { /*$goal 0 reachable*/ }
            return(t);
        }

        while (t.right != null)
        {
            { /*$goal 1 reachable*/ }
            t = t.right;
        }

        { /*$goal 2 reachable*/ }
        return(t);
    }
예제 #18
0
                public Enumerator(SmallDictionary <K, V> dict)
                    : this()
                {
                    AvlNode root = dict._root;

                    if (root != null)
                    {
                        // left == right only if both are nulls
                        if (root.Left == root.Right)
                        {
                            _next = dict._root;
                        }
                        else
                        {
                            _stack = new Stack <AvlNode>(dict.HeightApprox());
                            _stack.Push(dict._root);
                        }
                    }
                }
예제 #19
0
        private static void Replace(AvlNode target, AvlNode source)
        {
            AvlNode left  = source.Left;
            AvlNode right = source.Right;

            target.Balance = source.Balance;
            target.Key     = source.Key;
            target.Value   = source.Value;
            target.Left    = left;
            target.Right   = right;
            if (left != null)
            {
                left.Parent = target;
            }
            if (right != null)
            {
                right.Parent = target;
            }
        }
예제 #20
0
        private AvlNode Insert(AvlNode root, int value)
        {
            if (root == null)
            {
                return(new AvlNode(value));
            }

            if (value > root.GetValue())
            {
                root.SetRightChild(Insert(root.GetRightChild(), value));
            }
            else
            {
                root.SetLeftChild(Insert(root.GetLeftChild(), value));
            }

            SetHeight(root);

            return(Balance(root));
        }
예제 #21
0
 private void Insert(T x, ref AvlNode root)
 {
     //!!看清执行顺序很重要
     if (root == null)
     {
         root = new AvlNode(x);
     }
     else if (x.CompareTo(root.date) < 0)//左子树插入,左孩子高度肯定大于右孩子
     {
         //总是先Insert,更新height后,调整
         Insert(x, ref root.left);
         //用GetHeight是为了避免出现指向null的状况,因为没有null.height = -1
         if (GetHeight(root.left) - GetHeight(root.right) == 2)//平衡度
         {
             if (x.CompareTo(root.left.date) < 0)
             {
                 LL(ref root);
             }
             else
             {
                 LR(ref root);
             }
         }
     }
     else//右子树插入,右孩子高度肯定大于左孩子
     {
         Insert(x, ref root.right);
         if (GetHeight(root.right) - GetHeight(root.left) == 2)
         {
             if (x.CompareTo(root.right.date) > 0)
             {
                 RR(ref root);
             }
             else
             {
                 RL(ref root);
             }
         }
     }
     root.height = max(GetHeight(root.left), GetHeight(root.right)) + 1;//每次都是优先insert,再一级一级往上计算height,插入玩每个节点的height都是正确的
 }
예제 #22
0
        /// <summary>
        /// Inserts the specified key/value pair to the tree.
        /// </summary>
        /// <param name="key">The key of the element to insert.</param>
        /// <param name="value">The value of the element to insert. The value can be <c>null</c> for reference types.</param>
        /// <exception cref="System.ArgumentNullException">The key is null.</exception>
        /// <exception cref="System.ArgumentException">An element with the same key already exists in the tree.</exception>
        public override void Insert(TKey key, TValue value)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key", "The key is null.");
            }

            if (_root == null)
            {
                _root = new AvlNode {
                    Key = key, Value = value, Height = 0, Balance = 0
                };
                _nodeCount++;
                _version++;
                return;
            }

            AvlNode node = SearchNodeForInsertion(key) as AvlNode;

            if (node == null)
            {
                throw new ArgumentException("An element with the same key already exists in the tree.", "key");
            }

            if (_comparer.Compare(key, node.Key) < 0)
            {
                node.LeftChild = new AvlNode {
                    Key = key, Value = value, Parent = node, Height = 0, Balance = 0
                };
            }
            else
            {
                node.RightChild = new AvlNode {
                    Key = key, Value = value, Parent = node, Height = 0, Balance = 0
                };
            }

            Balance(node);
            _nodeCount++;
            _version++;
        }
예제 #23
0
        /// <summary>
        /// Inserts the specified key/value pair to the tree.
        /// </summary>
        /// <param name="key">The key of the element to insert.</param>
        /// <param name="value">The value of the element to insert. The value can be <c>null</c> for reference types.</param>
        /// <exception cref="System.ArgumentNullException">The key is null.</exception>
        /// <exception cref="System.ArgumentException">An element with the same key already exists in the tree.</exception>
        public override void Insert(TKey key, TValue value)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            if (this.root == null)
            {
                this.root = new AvlNode {
                    Key = key, Value = value, Height = 0, Balance = 0
                };
                this.nodeCount++;
                this.version++;
                return;
            }

            AvlNode node = this.SearchNodeForInsertion(key) as AvlNode;

            if (node == null)
            {
                throw new ArgumentException(CollectionMessages.KeyExists, nameof(key));
            }

            if (this.Comparer.Compare(key, node.Key) < 0)
            {
                node.LeftChild = new AvlNode {
                    Key = key, Value = value, Parent = node, Height = 0, Balance = 0
                };
            }
            else
            {
                node.RightChild = new AvlNode {
                    Key = key, Value = value, Parent = node, Height = 0, Balance = 0
                };
            }

            this.Balance(node);
            this.nodeCount++;
            this.version++;
        }
예제 #24
0
            public bool MoveNext()
            {
                switch (_action)
                {
                case Action.Right:
                    _current = _right;

                    while (_current.Left != null)
                    {
                        _current = _current.Left;
                    }

                    _right  = _current.Right;
                    _action = _right != null ? Action.Right : Action.Parent;

                    return(true);

                case Action.Parent:
                    while (_current.Parent != null)
                    {
                        AvlNode previous = _current;

                        _current = _current.Parent;

                        if (_current.Left == previous)
                        {
                            _right  = _current.Right;
                            _action = _right != null ? Action.Right : Action.Parent;

                            return(true);
                        }
                    }

                    _action = Action.End;

                    return(false);

                default:
                    return(false);
                }
            }
예제 #25
0
        private void BalanceAfterInsertion(AvlNode node, int balance)
        {
            while (node != null)
            {
                balance = (node.Balance += balance);
                switch (balance)
                {
                case 0:
                    return;

                case 2:
                    if (node.Left.Balance == 1)
                    {
                        RotateRight(node);
                    }
                    else
                    {
                        RotateLeftRight(node);
                    }
                    return;

                case -2:
                    if (node.Right.Balance == -1)
                    {
                        RotateLeft(node);
                    }
                    else
                    {
                        RotateRightLeft(node);
                    }
                    return;
                }
                AvlNode parent = node.Parent;
                if (parent != null)
                {
                    balance = ((parent.Left == node) ? 1 : (-1));
                }
                node = parent;
            }
        }
예제 #26
0
        private void HandleInsert(AvlNode node, AvlNode parent, K key, V value, bool add)
        {
            Node currentNode = node;

            do
            {
                if (CompareKeys(currentNode.Key, key))
                {
                    if (add)
                    {
                        throw new InvalidOperationException();
                    }

                    currentNode.Value = value;
                    return;
                }

                currentNode = currentNode.Next;
            } while (currentNode != null);

            AddNode(node, parent, key, value);
        }
예제 #27
0
        public bool Search(TKey key, out TValue value)
        {
            AvlNode avlNode = _root;

            while (avlNode != null)
            {
                if (_comparer.Compare(key, avlNode.Key) < 0)
                {
                    avlNode = avlNode.Left;
                    continue;
                }
                if (_comparer.Compare(key, avlNode.Key) > 0)
                {
                    avlNode = avlNode.Right;
                    continue;
                }
                value = avlNode.Value;
                return(true);
            }
            value = default(TValue);
            return(false);
        }
예제 #28
0
        //Source: https://www.geeksforgeeks.org/iterative-method-to-find-height-of-binary-tree/
        private int TreeHeight(AvlNode <int> node)
        {
            if (node == null)
            {
                return(0);
            }

            var q = new Queue <AvlNode <int> >();

            q.Enqueue(node);
            int height = 0;

            while (true)
            {
                var nodeCount = q.Count();
                if (nodeCount == 0)
                {
                    return(height);
                }
                height++;

                // Dequeue all nodes of current level and Enqueue all
                // nodes of next level
                while (nodeCount > 0)
                {
                    var newNode = q.Dequeue();
                    if (newNode.LeftChild != null)
                    {
                        q.Enqueue((AvlNode <int>)newNode.LeftChild);
                    }
                    if (newNode.RightChild != null)
                    {
                        q.Enqueue((AvlNode <int>)newNode.RightChild);
                    }
                    nodeCount--;
                }
            }
        }
예제 #29
0
파일: AvlTree.cs 프로젝트: DinkDev/Pliant
        private IEnumerator <T> GetEnumerator(AvlNode node)
        {
            if (node == null)
            {
                yield break;
            }

            var leftTree = GetEnumerator(node.Left);

            while (leftTree.MoveNext())
            {
                yield return(leftTree.Current);
            }

            yield return(node.Key);

            var rightTree = GetEnumerator(node.Right);

            while (rightTree.MoveNext())
            {
                yield return(rightTree.Current);
            }
        }
예제 #30
0
        internal AvlNode <T> Balance(AvlNode <T> node)
        {
            FixHeight(node);
            var balanceFactor = GetBalanceFactor(node);

            switch (balanceFactor)
            {
            case 2:
                if (GetBalanceFactor((AvlNode <T>)node.Right) < 0)
                {
                    node.Right = RotateToRight((AvlNode <T>)node.Right);
                }
                return(RotateToLeft(node));

            case -2:
                if (GetBalanceFactor((AvlNode <T>)node.Left) > 0)
                {
                    node.Left = RotateToLeft((AvlNode <T>)node.Left);
                }
                return(RotateToRight(node));
            }
            return(node);
        }
예제 #31
0
파일: AvlTree.cs 프로젝트: taoxiease/roops
    private boolean repOK_isOrdered(AvlNode n)
    {
        if (n==null)
              return true;

            int min = repOK_isOrderedMin(n);
            int max = repOK_isOrderedMax(n);

            return repOK_isOrdered(n, min, max);
    }
예제 #32
0
파일: AvlTree.cs 프로젝트: taoxiease/roops
    private boolean repOK_isOrdered(AvlNode n, int min, int max)
    {
        if ((n.element<min ) || (n.element>max))
                return false;

            if (n.left != null) {
                if (!repOK_isOrdered(n.left, min, n.element))
                    return false;
            }
            if (n.right != null) {
                if (!repOK_isOrdered(n.right, n.element, max))
                    return false;
            }
            return true;
    }
예제 #33
0
파일: AvlTree.cs 프로젝트: taoxiease/roops
 private int repOK_isOrderedMax(AvlNode n)
 {
     AvlNode curr = n;
       while (curr.right!=null) {
         curr = curr.right;
       }
       return curr.element;
 }
예제 #34
0
파일: AvlTree.cs 프로젝트: taoxiease/roops
 private int repOK_isOrderedMin(AvlNode n)
 {
     AvlNode curr = n;
       while (curr.left!=null) {
         curr = curr.left;
       }
       return curr.element;
 }