Exemplo n.º 1
0
        public static Node BalanceNode(Node node)
        {
            int         nodeCount = node.RightChilds + node.LeftChilds + 1;
            int         midVal    = node.FindMinimalNode((nodeCount + 1) / 2); // take middle value
            List <char> moves     = node.FindNodeMoves(midVal);                // find moves to find how come to new root

            for (int i = moves.Count - 1; i > 0; i--)
            {
                Node tempNode = node;
                for (int j = 0; j < i - 1; j++)
                {
                    tempNode = (moves[j] == 'l') ? tempNode.LeftNode : tempNode.RightNode;
                }

                if (moves[i - 1] == 'l')
                {
                    tempNode.LeftNode = (moves[i] == 'l') ?
                                        Node.RotateRight(tempNode.LeftNode) : Node.RotateLeft(tempNode.LeftNode);
                }
                else
                {
                    tempNode.RightNode = (moves[i] == 'l') ?
                                         Node.RotateRight(tempNode.RightNode) : Node.RotateLeft(tempNode.RightNode);
                }
            }

            if (moves.Count != 0)
            {
                node = (midVal < node.Number) ? Node.RotateRight(node) : Node.RotateLeft(node);
            }

            node.LeftNode  = (node.LeftNode != null) ? Node.BalanceNode(node.LeftNode) : null;
            node.RightNode = (node.RightNode != null) ? Node.BalanceNode(node.RightNode) : null;

            return(node);
        }