/**
* Created by yang on 12/29/16.
*/
public class PreorderToBST {
// TreeNode class
public static class TreeNode {
int val;
TreeNode left, right;
TreeNode(int x) {
this.val = x;
}
}
// convert function
public static TreeNode convertBST(int[] preorder) {
return helper(preorder, 0, preorder.length - 1);
}
// helper function, call recursively
private static TreeNode helper(int[] preorder, int start, int end) {
if (start == end) {
TreeNode node = new TreeNode(preorder[start]);
return node;
}
int rootVal = preorder[start];
int rootIndex = findIndex(preorder, rootVal, start, end);
TreeNode root = new TreeNode(rootVal);
root.left = helper(preorder, start + 1, rootIndex - 1);
root.right = helper(preorder, rootIndex, end);
return root;
}
// find index
private static int findIndex(int[] preorder, int rootVal, int start, int end) {
for (int i = start; i <= end; i++) {
if (preorder[i] > rootVal) {
return i;
}
}
return -1;
}
// print function
private static void printTree(TreeNode root) {
if (root == null) {
return;
}
System.out.print(root.val + " ");
printTree(root.left);
printTree(root.right);
}
// test, main function
public static void main(String[] args) {
int[] preorder = new int[]{6, 4, 3, 5, 10, 7, 11};
TreeNode root = convertBST(preorder);
System.out.println("Print preorder: ");
printTree(root);
}
}