Better Solution (bottom -up manner) : In this approach,We create the tree from bottom to root. This enables us to insert nodes in the tree in the same order as they appear in the list. So we don’t need to find the middle element as we are able to traverse list while inserting nodes to the tree. We first count the total number of nodes in the list.The list’s length could be found in O(N) time by traversing the entire list’s once. The recursive calls traverse the list and create tree’s nodes by the list’s order, which also takes O(N) time. Therefore, the overall run time complexity is still O(N). While constructing the BST, we also keep moving the list head pointer to next so that we have the appropriate pointer in each recursive call.

5 Thoughts on “Convert Sorted Linked list to balanced BST”

I think the 2nd approach won’t give the expected output.Below is my observation: The head remain same for all the recursive call for left child hence the root of the tree would be the first node of the linked list instead of the mid node of the list. E.g 2->4->6->8->10->12->14 The root of the tree would be 2 and left would also be 2.

1st approach also wouldn’t work while constructing right subtree. You should pass temp->next instead of head during below call. root->right = linkedListToBSTUtil(head, mid+1, end); There is no need to use ** as we are not modifying list.