Binary search trees have their best performance when they ar
Binary search trees have their best performance when they are balanced, which means that at each node, n, the height of the left subtree of n is within one of the height of the right subtree of n. Write a function (and a test program) which takes a sorted list of entries and produces a balanced binary search tree.
Solution
Please find my algorithm:
THe algorithm is as follows:
1. Insert into the tree middle element of the array
2. Insert (into left subtree) the left subarray elements
3. Insert (into right subtree) the right subarray elements
4. Recurse
Node createBalancedBinaryTree(int arr[], int start, int end){
// base case, we done with all elements of arr
if(end < start)
return null;
int mid = (start + end)/2; // getting middle index between start and end
Node n = new Node(arr[mid]); // creating new node of middle element of arr, start, end
n.left = createBalancedBinaryTree(arr, start, mid-1); // building left subtree of n
n.right = createBalancedBinaryTree(arr, mid+1, end); // building right subtree of n
// returning root node
return n;
}
