Minimal Tree
Minimal Tree: Given a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree with minimal height.
Link here to the repo to solve the problem
👉👌 Tips
A minimal binary tree has about the same number of nodes on the left of each node as on the right. Let'sfocus on just the root for now. How would you ensure that about the same number of nodes are on the left of the root as on the right?
You could implement this by finding the "ideal" next element to add and repeatedly calling insertValue.This will be a bit inefficient, as you would have to repeatedly traverse the tree.Try recursion instead. Can you divide this problem into subproblems?
Imagine we had a createMinimalTree method that returns a minimal tree for a given array (but for some strange reason doesn't operate on the root of the tree). Could you use this to operate on the root of the tree? Could you write the base case for the function? Great! Then that's basically the entire function.
👊 Solution 1
To create a tree of minimal height, we need to match the number of nodes in the left subtree to the number of nodes in the right subtree as much as possible.This means that we want the root to be the middle of the array, since this would mean that half the elements would be less than the root and half would be greater than it.
We proceed with constructing our tree in a similar fashion. The middle of each subsection of the array becomes the root of the node. The left half of the array will become our left subtree, and the right half of the array will become the right subtree.
One way to implement this is to use a simple root. insertNode(int v) method which inserts the value v through a recursive process that starts with the root node. This will indeed construct a tree with minimal height but it will not do so very efficiently. Each insertion will require traversing the tree, giving a total cost of 0(N log N)to the tree.
Alternatively, we can cut out the extra traversals by recursively using the createMinimalBST method. This method is passed just a subsection of the array and returns the root of a minimal tree for that array.
The algorithm is as follows:
- Insert into the tree the middle element of the array.
- Insert(into the left subtree) the left subarray elements.
- Insert(into the right sub tree) the right subarray elements. 4. Recurse.
BinaryTreeNode createMinimalBST(int[] array) {
return createMinimalBST(array, 0, array.length - 1);
}
BinaryTreeNode createMinimalBST(int[] array, int start, int end) {
if (end < start) return null;
int mid = (start + end) / 2;
BinaryTreeNode n = new BinaryTreeNode(array[mid]);
n.left = createMinimalBST(array, start, mid - 1);
n.right = createMinimalBST(array, mid + 1, end);
return n;
}
If we insert an array with the numbers from 1-9, the function will create a tree that looks like this:
Question borrowed from “Cracking the coding interview”