[wrong code]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int n;
public TreeNode buildTree(int[] preorder, int[] inorder) {
this.n= preorder.length;
return helper(preorder, inorder, 0, n-1, 0, n-1);
}
TreeNode helper(int[] preorder, int[] inorder, int l1, int r1, int l2, int r2){
if(out(l1, r1) || out(l2, r2)){
return null;
}
if(l1==r1 && l2 == r2){
return new TreeNode(preorder[l1]);
}
int rtval = preorder[l1];
int mid=0;
for(int i=l2;i<=r2;i++){
if(inorder[i]==rtval){
mid = i;
break;
}
}
TreeNode l = helper(preorder, inorder, l1+1, mid, l2, mid-1);
TreeNode r = helper(preorder, inorder, mid+1, r1, mid+1, r2);
TreeNode root = new TreeNode(rtval);
root.left = l;
root.right = r;
return root;
}
boolean out(int l, int r){
return l>r || !range(l) || !range(r);
}
boolean range(int i){
return i>=0 && i<n;
}
}```