<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>

class Solution {
public:
    unordered_map<TreeNode*,int> heights;//the given node has not height attribute
    
    TreeNode* leftRotation(TreeNode* A){
        TreeNode* B=A->right;
        A->right=B->left;
        B->left=A;
        updateHeight(A);
        updateHeight(B);
        return B;
    }
    int getHeight(TreeNode* t){
        if(!t) return -1;
        return heights[t];
    }
    int updateHeight(TreeNode* t){
       return heights[t]=max(getHeight(t->left),getHeight(t->right))+1;
    }
    TreeNode* insert(TreeNode* root,int x){
        if(!root){
            auto ans = new TreeNode(x);
            heights[ans]=0;
            return ans;
        }
        else if(x>root->val){
            root->right=insert(root->right,x);
            if(getHeight(root->right)-getHeight(root->left)==2){
                root=leftRotation(root);
            }
        }
        updateHeight(root);
        return root;
    }
    TreeNode* sortedListToBST(ListNode* head) {
        auto p=head;
        TreeNode* root=NULL;
        while(p){
            root=insert(root,p->val);
            p=p->next;
        }
        return root;
    }
};
28000