/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ import java.util.*; public class Solution { public TreeNode reConstructBinaryTree(int [] pre,int [] vin) { if(pre.length==0||vin.length==0){ return null; } return helper( pre, vin,0,pre.length-1,0,vin.length-1); } public static TreeNode helper (int[] pre,int[] vin,int pl,int pr,int vl,int vr){ if(pl>=pre.length||vl>=vin.length||pl>pr||vl>vr){ return null; } int val = pre[pl]; TreeNode root = new TreeNode(val); int count =vl; while(vin[count]!=val){ count++; } count-=vl; root.left =helper(pre,vin,pl+1,pl+count,vl,vl+count-1); root.right=helper(pre,vin,pl+count+1,pr,vl+count+1,vr); return root; } }