public static BinaryTreeNode<Integer> buildBinaryTree(Integer[] data, int i, int j) { if (i == j) { return new BinaryTreeNode<Integer>(data[i]); } else if (i > j) { return null; } else { int mid = (i + j) / 2; BinaryTreeNode<Integer> root = new BinaryTreeNode<Integer>( data[mid]); root.setLeft(buildBinaryTree(data, i + 1, mid)); root.setRight(buildBinaryTree(data, mid + 1, j)); return root; } }

Comments after running:

Something wrong with indices.

Input: 1 2 3 4 5 6 7

Output:

4

/ \

/ \

3 6

/ \ / \

3 4 6 7

Correction: Highlighted line 11 should be:root.setLeft(buildBinaryTree(data, i, mid-1));

Solution:

The solution is similar to my codes except that the highlighted line 3 and 4 are not necessary.Advertisements

## Build a binary tree from a sorted array with minimum height

02 Mar 2012 Leave a comment

in Questions from CareerCup Tags: Java, Tree