Skip to content

Instantly share code, notes, and snippets.

@thmain
Created February 22, 2016 05:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thmain/ca632f9b3eb116bc2fe0 to your computer and use it in GitHub Desktop.
Save thmain/ca632f9b3eb116bc2fe0 to your computer and use it in GitHub Desktop.
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment