Skip to content

Instantly share code, notes, and snippets.

@hrishikesh-mishra
Created March 14, 2017 12:28
Show Gist options
  • Save hrishikesh-mishra/9d9b770a05b0ccd3a3273a0f2f64cb3d to your computer and use it in GitHub Desktop.
Save hrishikesh-mishra/9d9b770a05b0ccd3a3273a0f2f64cb3d to your computer and use it in GitHub Desktop.
Binary Search Tree ADT
package com.hrishikesh.ns.tree;
/**
* Generate binary tree from sorted array
*
* @author hrishikesh.mishra
* @link http://hrishikeshmishra.com/generate-binary-tree-from-sorted-array/
*/
public class BinarySearchTreeGenerator {
public <E> BinaryTreeNode<E> generate(E[] array) {
return generate(array, 0, array.length - 1);
}
private <E> BinaryTreeNode<E> generate(E[] array, int start, int end) {
if (start > end) return null;
if (start == end) {
return new BinaryTreeNode<>(array[start]);
} else {
int mid = (start + end) / 2;
BinaryTreeNode<E> node = new BinaryTreeNode<>(array[mid]);
node.setLeft(generate(array, start, mid - 1));
node.setRight(generate(array, mid + 1, end));
return node;
}
}
}
class BinarySearchTreeGeneratorTest {
public static void main(String[] args) {
Integer[] array = {2, 5, 8, 16, 20};
BinarySearchTreeGenerator generator = new BinarySearchTreeGenerator();
BinaryTreePrinter printer = new BinaryTreePrinter();
printer.print(generator.generate(array));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment