Convert Sorted List to Balanced Binary Search Tree (BST)
November 27, 2010 in binary tree, linked list
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.
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).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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 *parent = new BinaryTree(list->data); parent->left = leftChild; list = list->next; parent->right = sortedListToBST(list, mid+1, end); return parent; } BinaryTree* sortedListToBST(ListNode *head, int n) { return sortedListToBST(head, 0, n-1); } |


Anonymous said on November 27, 2010
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).
Rocky said on November 25, 2012
I think we could convert the recursive version to iterative version through using Stack.
Holger Dürer said on November 29, 2010
Now, is there a version as neat and tidy as this which does not require you to know the length of the list beforehand?
Anonymous said on November 28, 2011
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.
abayley said on November 29, 2010
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?
godheadatomic said on November 29, 2010
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.
1337c0d3r said on November 29, 2010
@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).
1337c0d3r said on November 29, 2010
@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)).
1337c0d3r said on November 29, 2010
@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?
1337c0d3r said on November 29, 2010
@godheadatomic:
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)).
Matthew Leon Grinshpun said on November 29, 2010
@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
Anonymous said on November 30, 2010
@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.
Algoseekar said on March 6, 2011
@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
hendry said on March 10, 2011
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.
Andliory said on March 20, 2011
I agree with 12L. maybe it’s a bug
sheen said on March 22, 2011
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.
sheen said on March 22, 2011
Please ignore the previous post I did. Now I understand. Very good solution.
algorist2011 said on March 31, 2011
Hi can you please explain the approach above…. this is Pretty recursive in nature algorithm. And i am not getting the approach.. Please examplify!!
xTristan said on April 4, 2011
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:
xTristan said on April 4, 2011
the for loop above got messed up after submitting. re-attach:
for (int i = 0; i < length; i++)
tree_nodes[i] = new Node(head.data);
head = head.next;
}
speeddy said on April 5, 2011
So you basically convert the sorted list to sorted array.
Then use the algorithm sorted array to bst?
xTristan said on April 5, 2011
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.
ying xie said on March 29, 2013
I agree with you.
“parent” should be the mid node.
Raj said on May 9, 2011
Very smart idea and implementation, thanks!
Greed said on July 3, 2011
Hey can you write code change a sorted doubly linked list to BST
wwwyhx said on December 30, 2011
Inplace makes sense
NODE* _inner_construct(NODE* pHead, int nLen)
{
if (NULL == pHead || nLen <= 0)
return NULL;
NODE* pMid = pHead;
for (int i = 0; i pRgt;
pMid->pLft = _inner_construct(pHead, nLen/2);
pMid->pRgt = _inner_construct(pMid->pRgt, nLen-1-nLen/2);
return pMid;
}
opoopo said on May 23, 2012
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) {
list = head;
return sortedListToBST(n);
}
}
Prateek Caire said on August 14, 2012
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).
Amit Kumar Swami said on August 18, 2012
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.
LT said on September 9, 2012
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) {
return sortedListToBST(head, 0, n-1);
}
SomeRandomDude said on September 29, 2012
Amazing. I had the O(nlogn) solution in mind only
Benny said on October 13, 2012
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. : )
sean said on November 30, 2012
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.
ja said on February 15, 2013
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….
Punit Patel said on March 8, 2013
Here is the iterative version
butlerain said on April 7, 2013
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(){
buildBST(head, N);
}