## # 109. Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

``````Given the sorted linked list: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

0
/ \
-3   9
/   /
-10  5

``````

### # Solution

Approach 1: use 2 pointers to find root (at the middle of linked list), then recurse. Time: `NlogN`. Extra space: `logN` (stack).

Approach 2: convert to array, then recurse. Time: `N`. Extra space: `logN` (stack) and `N` (array).

Approach 3: Simulate what an inorder traversal does: recursively construct the left subtree, then use the current head as root, then recursively contruct the right subtree. Maintain the invariant that once a linkedlist node is used, the current head moves forward. Time: `N`. Extra space: `logN` (stack).

### # Code (Python)

Approach 3:

``````    def sortedListToBST(self, head: 'ListNode') -> 'TreeNode':
return None
len_of_list = 0
while node:
len_of_list += 1
node = node.next
return self._to_bst(0, len_of_list - 1)

# the start, end and mid pointers are there to limit the base case (make sure the base case happens)
def _to_bst(self, start, end):
if start > end:
return None
mid = (start + end) // 2
left = self._to_bst(start, mid - 1)
root.left = left
root.right = self._to_bst(mid + 1, end)
return root
``````

### # Code (C++)

Approach 1:

``````/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// Recursion.
class Solution {
public:
return NULL;
while (fast && fast->next)
{
fast = fast->next->next;
slow = slow->next;
prev = prev->next;
}
TreeNode *root = new TreeNode(slow->val);
prev->next = NULL;
root->right = sortedListToBST(slow->next);
return root;
}
};
``````

Approach 3:

``````// Inorder simulation.
class Solution {
private:
ListNode *curr;
{
return NULL;
TreeNode *left = formBst(head, mid - 1);
TreeNode *root = new TreeNode(curr->val);
curr = curr->next;
root->left = left;
root->right = formBst(mid + 1, tail);
return root;
}
public: