Skip to content

Instantly share code, notes, and snippets.

@hkasera
Created September 5, 2015 11:03
Show Gist options
  • Save hkasera/649ee771990fafb07778 to your computer and use it in GitHub Desktop.
Save hkasera/649ee771990fafb07778 to your computer and use it in GitHub Desktop.
Sorted Array to Binary Search Tree
class Node{
int val;
Node left;
Node right;
}
class Tree{
Node root;
}
public class BST {
public static void main(String args[] ) throws Exception {
int a[] = {1,2,3,4,5,6};
Node root;
int min = 0;
int max = a.length - 1;
root = bst(a,min,max);
printTree(root);
}
public static Node bst(int[] arr, int min, int max){
if(max >= min){
int mid = (max+min)/2;
Node root = new Node();
root.val = arr[mid];
root.left = bst(arr,min,mid-1);
root.right = bst(arr,mid+1,max);
return root;
}else{
return null;
}
}
public static void printTree(Node root){
if(root == null){
return;
}
if(root.left!=null){
printTree(root.left);
}
System.out.println(root.val);
if(root.right!=null){
printTree(root.right);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment