Tuesday, 21 January 2014

Question :

Given an array you need to convert it into an balanced BST(Binary Search Tree).

Example :

Solution :

Given an array first step would be to sort it. You can probably use quick sort which will take average time O(NlogN) complexity. Once you have sorted you can apply following algorithm to convert it into a balance BST.

Get the Middle of the array and make it root.

Recursively do same for left half and right half.

Get the middle of left half and make it left child of the root created in step 1.

Get the middle of right half and make it right child of the root created in step 1.