<p>Given the <code>head</code> of a singly linked list where elements are sorted in <strong>ascending order</strong>, convert <em>it to a </em><span data-keyword="height-balanced"><strong><em>height-balanced</em></strong></span> <em>binary search tree</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/08/17/linked.jpg" style="width: 500px; height: 388px;" />
<pre>
<strong>Input:</strong> head = [-10,-3,0,5,9]
<strong>Output:</strong> [0,-3,9,-10,null,5]
<strong>Explanation:</strong> One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> head = []
<strong>Output:</strong> []
</pre>

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

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

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
# 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 sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:

        def ln(node):
            cnt = 0
            while node:
                cnt += 1
                node = node.next
            return cnt
        
        l = ln(head)

        def back(l, r): 
            nonlocal head
            
            if l == r:
                return None

            mid = (l + r) // 2

            left = back(l, mid)

            node = TreeNode(head.val)
            node.left = left

            head = head.next 
            
            node.right = back(mid + 1, r)
            
            return node
    
        return back(0, l)














        # if not head:
        #     return None

        # def printer(node):
        #     print(node)
        #     if not node:
        #         return None
        #     printer(node.left)
        #     printer(node.right)
            
            

        # def find_mid(node, last):

        #     slow = node
        #     fast = node

        #     while fast != last and fast.next != last:
        #         slow = slow.next
        #         fast = fast.next.next

        #     return slow

        # def back(l, r):
            
        #     if l == r:
        #         return None

        #     mid = find_mid(l, r)

        #     node = TreeNode(mid.val)

        #     node.left = back(l, mid)
        #     node.right = back(mid.next, r)

        #     return node
        
        # printer(None)

        # return back(head, None)


20900