## Convert Sorted List to Balanced Binary Search Tree (BST)

November 27, 2010

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

If you have not checked out my previous post: Convert Sorted Array to Balanced Binary Search Tree (BST), you should check it out now as this solution is built upon the previous solution.

Things get a little more complicated when you have a singly linked list instead of an array. Please note that in linked list, you no longer have random access to an element in O(1) time.

Singly-linked lists contain nodes which have a data field as well as a next field, which points to the next node in the linked list.

Naive Solution:
A naive way is to apply the previous solution directly. In each recursive call, you would have to traverse half of the list’s length to find the middle element. The run time complexity is clearly O(N lg N), where N is the total number of elements in the list. This is because each level of recursive call requires a total of N/2 traversal steps in the list, and there are a total of lg N number of levels (ie, the height of the balanced tree).

Hint:
How about inserting nodes following the list’s order? If we can achieve this, we no longer need to find the middle element, as we are able to traverse the list while inserting nodes to the tree.

Best Solution:
As usual, the best solution requires you to think from another perspective. In other words, we no longer create nodes in the tree using the top-down approach. We create nodes bottom-up, and assign them to its parents. The bottom-up approach enables us to access the list in its order while creating nodes.

Isn’t the bottom-up approach neat? Each time you are stucked with the top-down approach, give bottom-up a try. Although bottom-up approach is not the most natural way we think, it is extremely helpful in some cases. However, you should prefer top-down instead of bottom-up in general, since the latter is more difficult to verify in correctness.

Below is the code for converting a singly linked list to a balanced BST. Please note that the algorithm requires the list’s length to be passed in as the function’s parameters. 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).

VN:F [1.9.22_1171]
Convert Sorted List to Balanced Binary Search Tree (BST), 4.8 out of 5 based on 44 ratings

### 46 responses to Convert Sorted List to Balanced Binary Search Tree (BST)

1. Pretty darn smart and clean.
I wonder if there is an iterative version, since you have the size n, you can literally scratch out the tree.(knowing exactly where nodes should be placed).

VA:F [1.9.22_1171]
0
• I think we could convert the recursive version to iterative version through using Stack.

VN:F [1.9.22_1171]
0
2. Now, is there a version as neat and tidy as this which does not require you to know the length of the list beforehand?

VA:F [1.9.22_1171]
0
• If there could have been one such algo in O(N) then why would avl tree insertion take O(NlogN) for inserting N elements (and suppose N is not known).
Hence we need to know the value of N in advance along with the data.
It is similar to buildHeap where build Heap takes O(N) if all numbers are given aprior . But in our case we have numbers in sorted order.

VA:F [1.9.22_1171]
0
• As the algorithm in O(n), we only add a constant factor by iterating over the list once to get its length. Therefore, knowing the length or not is (mostly) irrelevant.

VA:F [1.9.22_1171]
0
3. I see that the *&list parameter is modified. Wondering if there is a solution that does not modify *&list e.g. for languages like Haskell?

VA:F [1.9.22_1171]
0
4. An iterative approach would be to traverse the list in order, and at each node insert into your new binary tree and rebalance (rotate) if necessary. This would work for a list of unknown length.

VA:F [1.9.22_1171]
0
5. @Anonymous:
The solution is highly recursive and definitely isn't a simple tail recursion, therefore converting it to an iterative one is definitely non-trivial.

However, I have an iterative solution in mind.

Since we know the size n, we already know the height of the tree, and how many leaves the tree has (ie, how many nodes at the bottom level).

We first create an empty tree with the correct structure, then do an iterative in-order traversal of the tree setting values into the nodes as we traverse the list. The overall complexity is still O(N).

VA:F [1.9.22_1171]
+5
6. @Holger:
Without knowing the length of the list, you wouldn't know how the balanced tree structure is like, since you don't know its height and such. You have to re-balance the tree each time you insert an element, which complexity is O(log(N)).

VA:F [1.9.22_1171]
0
7. @abayley:
The list parameter is required to be passed as reference, as its pointer is changed as we traverse the list. If you couldn't use reference in a language, maybe a simple global variable will do?

VA:F [1.9.22_1171]
0
I assume your rebalance (rotate) operation would take O(log(N)) time. Therefore, your iterative approach's run time complexity is O(N log(N)).

VA:F [1.9.22_1171]
0
9. @abayley and 1337c0d3r:

I have posted a Haskell solution as a gist: https://gist.github.com/720950

Once I get my new blog up and running I intend to write a bit about it, but I hope my style is fairly clear.

–Matthew Leon Grinshpun

VA:F [1.9.22_1171]
0
10. @1337c0d3r
About your response to @abayley, does the pointer have to be a reference? Since we are passing it as an argument, is it possible to just use a pointer?
I guess I'm just confused why it has to be passed by reference.

VA:F [1.9.22_1171]
0
11. @ihas1337code will create BST or Binary Tree please reply asap…i think it will create binary tree try for linked list has data values as 1 2 3 4 5..& please let mem know

VA:F [1.9.22_1171]
0
12. I think there is a bug in line 9
parent->right = sortedListToBST(list, mid+1, end);
mid+1 and end is right for the function input, but list is already updated at line 5 and line 8, so the index mid+1 to end is no longer right here.

VA:F [1.9.22_1171]
0
13. I agree with 12L. maybe it’s a bug

VA:F [1.9.22_1171]
0
14. I may be wrong. I think the implementation is incorrect.

list = list->next;

We should change this statement to while loop until we meet the mid one. Otherwise, there is no point we pass in start and end. And the tree wouldn’t be balanced bst.

Correct me if I am wrong.

VA:F [1.9.22_1171]
0
• Please ignore the previous post I did. Now I understand. Very good solution.

VA:F [1.9.22_1171]
0
• Hi can you please explain the approach above…. this is Pretty recursive in nature algorithm. And i am not getting the approach.. Please examplify!!

VA:F [1.9.22_1171]
0
• Because the variable is passed as a reference, the multiple increments that sheen was expecting actually do happen in the recursion.

VA:F [1.9.22_1171]
0
15. This approach is elegant. Great! Thanks!

For languages without passing-by-reference arguments, this might be a bit trickier.

Would this simpler algo work:

Given you know the length of your list (the same assumption you are making for your algo. If not, an extra linear scan would suffice as well), create an array tree_nodes[len]. Note this is not extra space because in order to get the tree constructed you need that much space anyway.

Start from the beginning of your list, for each list node at position i, create a tree node and place it in tree_nodes[i].

After the entire list is scanned, you have an array converted from the linked list. From that everything is trivial.

I admit this is actually 2N because it requires a linear visit to the tree_nodes[len] array. We may be able to get rid of this if at the first loop we can figure out the parent index and child index of each node at constant time. Any thoughts?

pseudo code:

VA:F [1.9.22_1171]
+1
• the for loop above got messed up after submitting. re-attach:

for (int i = 0; i < length; i++)
}

VA:F [1.9.22_1171]
0
• So you basically convert the sorted list to sorted array.

Then use the algorithm sorted array to bst?

VA:F [1.9.22_1171]
0
• Essentially yes, but not using the exact array algorithm. The first loop creates the tree nodes already, therefore, space-wise, you don’t waste any space comparing to the algorithm in this post.

Time-complexity, yes, although both are linear, this approach requires an extra loop, which is bad. But on the other hand, recursion comes with its own price as well. Recursion requires pushing/popping on the call stack each time you recurse, which are not free operations.

VA:F [1.9.22_1171]
0
• I agree with you.
“parent” should be the mid node.

VA:F [1.9.22_1171]
0
16. Raj said on May 9, 2011

Very smart idea and implementation, thanks!

VA:F [1.9.22_1171]
0
17. Hey can you write code change a sorted doubly linked list to BST

VA:F [1.9.22_1171]
0
18. Inplace makes sense
{
if (NULL == pHead || nLen <= 0)
return NULL;

for (int i = 0; i pRgt;

pMid->pRgt = _inner_construct(pMid->pRgt, nLen-1-nLen/2);

return pMid;
}

VA:F [1.9.22_1171]
-1
19. Parameter start, end in 1337′s code is not necessary, we can use len instead, Java code below:

public class Test {
public static Node list = null;
public static TreeNode sortedListToBST(int len) {
if (len <= 0) return null;
TreeNode leftChild = sortedListToBST(len/2);
TreeNode parent = new TreeNode(list.key);
parent.left = leftChild;
list = list.next;
parent.right = sortedListToBST(len-len/2-1);
return parent;
}
public static TreeNode sortedListToBST(Node head, int n) {
return sortedListToBST(n);
}
}

VA:F [1.9.22_1171]
0
20. Nice solution. However, unlike BST to Linked list solution where Binary tree nodes were used to represent a node in linked list, this solution creates new binary tree nodes. Thus O(N) space is required. i wonder if any solution exists without using extra space? One you already mentioned above, but that take O(NlogN).

VA:F [1.9.22_1171]
0
21. I think there is a bug in program. the line 5 should be placed after line 8. when list is updated. Otherwise left child will add same data as root.

VA:F [1.9.22_1171]
0
22. I guess the way to reconstruct a balanced BST is similar to the way of traversing a tree. This question reconstruct the tree using “in-order” traverse.
So if we have another question like “Give a linked list, the numbers in front half size of list is increasing and in back half size of list in decreasing, convert the linked list to balanced BST”.
Can we just simply change answer of this question to “post order” traverse?

BinaryTree* sortedListToBST(ListNode *& list, int start, int end) {
if (start > end) return NULL;
// same as (start+end)/2, avoids overflow
int mid = start + (end – start) / 2;
BinaryTree *leftChild = sortedListToBST(list, start, mid-1);
BinaryTree *rightChild = sortedListToBST(list, mid+1, end);
BinaryTree *parent = new BinaryTree(list->data);
parent->left = leftChild;
parent->right = rightChild;
list = list->next;

return parent;
}

BinaryTree* sortedListToBST(ListNode *head, int n) {
}

VN:F [1.9.22_1171]
0
23. Amazing. I had the O(nlogn) solution in mind only

VA:F [1.9.22_1171]
0
24. Converting a Linked List to an Array is O(n).
Then use http://www.leetcode.com/2010/11/convert-sorted-array-into-balanced.html.

The solution would still be O(n).
Much easier and reuse code is always nice to iron out bugs. : )

VA:F [1.9.22_1171]
0
25. private TreeNode sortedListToBST(ref ListNode node, int start, int end)
{
if (start > end)
{
return null;
}

int mid = start + (end – start) >> 1;
var l = sortedListToBST(ref node, start, mid – 1);
var r = sortedListToBST(ref node, mid + 1, end);
TreeNode p = new TreeNode(node.Val);
p.LeftChild = l;
p.RightChild = r;
node = node.Next;
return p;
}

tried this in c#, got StackOverflow.

VA:F [1.9.22_1171]
0
26. do we really need to know the length of the link list?

We can start from head. We know it should correspond to 2^0 = 1 in bst. we know we need to stop at 2^1 link-list node, then we know we need to stop at 2^2 link list node, 2^3 and so on….

VA:F [1.9.22_1171]
0
27. Here is the iterative version

VA:F [1.9.22_1171]
0
28. void buildBST(ListNode * pn, int size){
TreeNode * pt;
if(size==0){
return null;
}else if(size == 1){
pt->val=pn->val;
pt->left = null;
pt->right = null;
return pt;
}else {
ListNode * p=pn;
int middle = size/2;
for(int i = 0; inext;
}
pt->val=p->val;
pt->left = buildBST(pn, size/2);
pt->right = buildBST(p->next, size/2-1);
return pt;
}
}

void main(){
}

VN:F [1.9.22_1171]
0
29. Hi, why the following code can’t pass the online judge? It’s basically the same code as in the “Best Solution” section, just in Java. Thank you for any input.

VN:F [1.9.22_1171]
0
• what kind of error did you get? I think because in Java parameter are passed by reference, so the list didn’t get changed. correct me if I’m wrong.

VN:F [1.9.22_1171]
0
30. AJ said on July 8, 2013

Nice. Pretending to walk a tree in-order and building it while visiting!

VA:F [1.9.22_1171]
0
31. Solution for fixing Java’s no-argument-passed-with-pointer issue: place the head of the list in an array, and this gives us a pseudo “pointer”.

VN:F [1.9.22_1171]
+1
• Why not using a member variable here. Then you do not even need to pass in the head.

VA:F [1.9.22_1171]
0
32. cool! To understand this algorithm, just remember that the function
BinaryTree* sortedListToBST(ListNode *& list, int start, int end) actually does the following two main things:
1. It creates a balanced BST for nodes from “start” to “end”
2. During the process in creating the BST, it also moves the “list” pointer to point at the node after the “end” node.

VA:F [1.9.22_1171]
+2