<p>Given the <code>root</code> of a binary search tree, return <em>a <strong>balanced</strong> binary search tree with the same node values</em>. If there is more than one answer, return <strong>any of them</strong>.</p>

<p>A binary search tree is <strong>balanced</strong> if the depth of the two subtrees of every node never differs by more than <code>1</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/08/10/balance1-tree.jpg" style="width: 500px; height: 319px;" />
<pre>
<strong>Input:</strong> root = [1,null,2,null,3,null,4,null,null]
<strong>Output:</strong> [2,1,3,null,null,null,4]
<b>Explanation:</b> This is not the only correct answer, [3,1,4,null,2] is also correct.
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/08/10/balanced2-tree.jpg" style="width: 224px; height: 145px;" />
<pre>
<strong>Input:</strong> root = [2,1,3]
<strong>Output:</strong> [2,1,3]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
	<li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li>
</ul>

from collections import deque
from math import log
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def balanceBST(self, root: TreeNode) -> TreeNode:
        dummy = TreeNode()
        dummy.right = root
        
        def tree_to_vine(root):
            size = 0
            tail = root
            rest = tail.right
            while rest:
                if rest.left is None:
                    tail = rest
                    rest = rest.right
                    size += 1
                else:
                    temp = rest.left
                    rest.left = temp.right
                    temp.right = rest
                    rest = temp
                    tail.right = temp
            return size
        size = tree_to_vine(dummy)

        def compress(root, iters):
            scanner = root
            for _ in range(iters):
                child = scanner.right
                scanner.right = child.right
                scanner = scanner.right
                child.right = scanner.left
                scanner.left = child
        print(size)
        def balance(root, size):
            extra = size + 1 - 2**int(log(size + 1, 2))
            print(extra)
            compress(root, extra)
            size -= extra
            while size > 1:
                compress(root, int(size / 2))
                size = int(size / 2)
        
        balance(dummy, size)
        return dummy.right



        
20600