Build a binary tree from a sorted array with minimum height

	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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: