**Objective:** Given a sorted array with unique elements, Create a binary search tree with minimal height.

**Why minimal height is important : **

We can do the linear scan to the array and make the first element as root and insert all other elements into the tree but in that case tree will be ** skewed **, which means all the nodes of the tree will be on the one side of the root so the height of the tree will be equal to the number of elements in the array. So here our objective is to keep the tree balanced as much as possible.

**What is balanced Tree: **A balanced tree is a tree in which difference between heights of sub-trees of any node in the tree is not greater than one. To read more about balanced tree, click here

**Input:** A one dimensional array

**Output: **Binary Search Tree of Minimal Height

**Example: **

**Approach:**

**Recursion:**

- Get the middle of the array
- make it as root.
*(By doing this we will ensure that half of the elements of array will be on the left side of the root and half on the right side*.) - Take the left half of the array, call recursively and add it to root.left.
- Take the right half of the array, call recursively and add it to root.right.
- return root.

**Complete Code:**

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.

Learn more about bidirectional Unicode characters

public class SortedArrayToBST { | |

public BSTNode convert(int [] arrA, int start, int end){ | |

if(start>end){ | |

return null; | |

} | |

int mid = (start + end)/2; | |

BSTNode root = new BSTNode(arrA[mid]); | |

root.left = convert(arrA, start, mid–1); | |

root.right =convert(arrA, mid+1, end); | |

return root; | |

} | |

public void displayTree(BSTNode root){ | |

if(root!=null){ | |

displayTree(root.left); | |

System.out.print(" " + root.data); | |

displayTree(root.right); | |

} | |

} | |

public static void main(String args[]){ | |

int [] arrA = {2,3,6,7,8,9,12,15,16,18,20}; | |

SortedArrayToBST s = new SortedArrayToBST(); | |

BSTNode x = s.convert(arrA, 0, arrA.length–1); | |

System.out.println("Tree Display : "); | |

s.displayTree(x); | |

} | |

} | |

class BSTNode{ | |

int data; | |

BSTNode left; | |

BSTNode right; | |

public BSTNode(int data){ | |

this.data = data; | |

left = null; | |

right = null; | |

} | |

} |

**Output:**

Tree Display : 2 3 6 7 8 9 12 15 16 18 20