ref: http://www.cnblogs.com/springfor/p/3884034.html 解释的很详细
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder==null|| inorder==null) return null;
int pl = preorder.length;
int il = inorder.length;
return findRoot(preorder, 0, pl-1, inorder, 0, il-1);
}
public TreeNode findRoot(int[] preorder, int pstart, int pend, int[] inorder, int istart, int iend){
if(pend < pstart || iend < istart) return null;
int rootval = preorder[pstart];
TreeNode root = new TreeNode(rootval);
int rootInd = istart;
while(inorder[rootInd]!=rootval){
rootInd++;
}
int len =rootInd-istart;
root.left = findRoot(preorder, pstart+1, pstart+len, inorder, istart, rootInd-1);
root.right = findRoot(preorder, pstart+len+1, pend, inorder, rootInd+1, iend);
return root;
}
}