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

November 25, 2010 in binary tree, divide and conquer

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

If you are having hard time in understanding my previous post: Largest Binary Search Tree (BST) in a binary tree, do not fret as that problem is a comparably trickier tree problem for an interview session. But that should not be an excuse for you to not improve your ability to think recursively (without your brain stack being overflowed of course ).

Recursion is a very powerful problem-solving mechanism, and you would not go very far without it during an interview session. Here might be an easier tree problem for you to start before you hop on those challenging ones.

**Hint:**

This question is highly recursive in nature. Think of how binary search works.

**Solution:**

If you would have to choose an array element to be the root of a balanced BST, which element would you pick? The root of a balanced BST should be the middle element from the sorted array.

You would pick the middle element from the sorted array in each iteration. You then create a node in the tree initialized with this element. After the element is chosen, what is left? Could you identify the sub-problems within the problem?

There are two arrays left — The one on its left and the one on its right. These two arrays are the sub-problems of the original problem, since both of them are sorted. Furthermore, they are subtrees of the current node’s left and right child.

The code below creates a balanced BST from the sorted array in *O*(*N*) time (*N* is the number of elements in the array). Compare how similar the code is to a binary search algorithm. Both are using the divide and conquer methodology.

1 2 3 4 5 6 7 8 9 10 11 12 13 | BinaryTree* sortedArrayToBST(int arr[], int start, int end) { if (start > end) return NULL; // same as (start+end)/2, avoids overflow. int mid = start + (end - start) / 2; BinaryTree *node = new BinaryTree(arr[mid]); node->left = sortedArrayToBST(arr, start, mid-1); node->right = sortedArrayToBST(arr, mid+1, end); return node; } BinaryTree* sortedArrayToBST(int arr[], int n) { return sortedArrayToBST(arr, 0, n-1); } |

**Further Thoughts:**

Consider changing the problem statement to “Converting a singly linked list to a balanced BST”. How would your implementation change from the above?

Check out my next post: Convert Sorted List to Balanced Binary Search Tree (BST) for the best solution.

Convert Sorted Array to Balanced Binary Search Tree (BST),
Anonymous said on November 25, 2010

Nice post.

Happy Thanksgiving.

+4Anonymous said on November 26, 2010

I'm having trouble thinking of an approach to the linked list case.. any hints/tips ?

01337c0d3r said on November 26, 2010

The hint is to modify the above solution for the linked list case (It is actually few lines of code changes for the linked list case).

A naive solution would be O(N lg N). The biggest challenge is linked list does not permit random access in O(1). Could you try to insert the node by the list's order?

0anshul said on March 1, 2011

This still does not produce a balanced tree.

0aznslayer said on January 21, 2014

it does

+1Algoseekar said on March 6, 2011

Please Check Your Program it Not Seems to be correct , i have check your program & m getting difficulty or might be i am not getting it please rewrite it with simple example say we have sorted array 1,2,3,4,5 so please show me output how constructed BST looks like..please try to give program..asap..thanks in advance..

0Algoseekar said on March 11, 2011

Please Check Your Program it Not Seems to be correct , i have check your program & m getting difficulty or might be i am not getting it please rewrite it with simple example say we have sorted array 1,2,3,4,5 so please show me output how constructed BST looks like..please try to give program..asap..thanks in advance..

Please Reply ASAP

+1Lucy said on April 25, 2011

I think the solution is write. For sorted array 1, 2, 3, 4, 5, the result is

3

/ \

1 4

\ \

2 5

0XmasteR said on May 12, 2011

GREAT IDEA!

This helped me alot to make a cool balanced deep copy of my BST

0m said on May 17, 2011

Hey,

You have a brilliant site! The problems are very interesting, and your explanations are great.

About this one:

It doesn’t seem to handle duplicates in the array (am i mistaken?). I think it be solved without breaking the O(n) guarantee as follows:

before making the recursive calls,

Then the recursive calls should be for

and

.

Does that seem right? i may have missed some boundary conditions somewhere, sorry

cheers,

..m

0saurya said on April 13, 2012

Hi, can some one help me wid this,

Form a labelled binary tree of message “ROAD IS GOOD”.

and mail me its answer..to my mail id-

sauryanjan@gmail.com

0hooha said on August 20, 2012

“The code below creates a balanced BST from the sorted array in O(N) time”,why not O(lgN)?

0Liang Zou said on May 5, 2013

http://en.wikipedia.org/wiki/Master_theorem

0mrityunjay said on November 17, 2012

This program doesn’t work for size =1

0mrityunjay said on November 18, 2012

Sorry for last comment

0moshe said on December 22, 2012

hi, if i want to add the parent address – is it possible ?

the code does not add the parent address, only the left and right sons. thanks!

0theGhost said on September 12, 2013

just change the signature adding an extra ‘parent’ param:

Hope it helps !

0Kwyx said on August 12, 2013

A more interesting problem would be to inplace convert the sorted Arr into BST array representation. Assume the array is extended till the (next power of 2)-1 or something like that.

0doil said on January 24, 2014

hey, thanks for the articale.

What is the best way to make the BST to red-black tree?

The purpose is to build a red black tree in O(n) from sorted array.

Thanks.

0NAVLOK MISHRA said on April 18, 2014

I think it is not O(N) it should be O(NlogN)

-1NAVLOK MISHRA said on April 18, 2014

sorry for the above comment

it is OK.. O(n)

0yaz720 said on April 20, 2014

No need to worry about overflow:

Both (start+end)/2 and start + (end-start) / 2 always give you the same result

0Yunsong Wu said on June 17, 2014

It can cause overflow. Assuming the maximum integer PC can operate is 10, and start = 5, end = 6. If we use (start+end)/2, we will have overflow when doing start+end. But there will be no such problem when doing start+(end-start)/2.

0Lal Shah said on July 4, 2014

Take the middle element of the input array and mark it as the root.

Build up left and right sub trees recursively with the left and right sub array of the array.

Return the tree.

For explanation and code http://www.algoqueue.com/algoqueue/default/view/8847360/sorted-array-to-binary-search-tree

0Saurabh said on July 9, 2014

Thanks!! Very Nice Post..!!!!

0Alisia said on July 11, 2014

It’s hard to find your blog in google. I found it on 20 spot, you should build quality backlinks , it will help you to increase traffic.

I know how to help you, just search in google –

k2 seo tips

0