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),
Nice post.

Happy Thanksgiving.

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

0The 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?

+1This still does not produce a balanced tree.

-1it does

+1Please 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..

0Please 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

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

3

/ \

1 4

\ \

2 5

-2GREAT IDEA!

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

0Hey,

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

0Hi, 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

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

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

0This program doesn’t work for size =1

0Sorry for last comment

0hi, 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!

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

Hope it helps !

0A 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.

0hey, 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.

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

-1sorry for the above comment

it is OK.. O(n)

0No need to worry about overflow:

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

0It 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.

0Pingback: DS conversion | mybookmarks

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

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

0Pingback: LeetCode | techinterviewsolutions

http://www.youtube.com/watch?v=VCTP81Ij-EM Here is video for converting sorted array to balanced BST.

+1