Write a algorithm to create binary tree with min height.
Algorithm
import java.util.Arrays; import com.omt.learn.algo.util.tree.TreeNode; public class BinaryTreeWithMinHeight { public static void main(String[] args) { int a[] = { 1, 2, 3, 4, 5, 6, 7 }; Arrays.sort(a); TreeNode tn = createTreeWithMinHeight(a, 0, a.length - 1); } public static TreeNode createTreeWithMinHeight(int a[], int start, int end) { if (start > end) { return null; } int middle = (start + end) / 2; TreeNode tn = new TreeNode(createTreeWithMinHeight(a, start, middle - 1), createTreeWithMinHeight(a, middle + 1, end), String.valueOf(a[middle])); return tn; } }
ThreeNode.java
public class TreeNode { public String nodeName = ""; public boolean isVisited = false; public int value = 0; public TreeNode leftNode = null; public TreeNode rightNode = null; public TreeNode() { // TODO Auto-generated constructor stub } public TreeNode(String name) { nodeName = name; } public TreeNode(TreeNode left, TreeNode right, String name) { leftNode = left; rightNode = right; nodeName = name; } }