/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { return build(preorder,0,preorder.length-1,inorder,0,inorder.length-1); } public TreeNode build(int[] preorder,int preStrat,int preEnd,int[] inorder,int inStrat,int inEnd ){ if(preStrat>preEnd) return null; int rootVal = preorder[preStrat]; int index = 0; for(int i=inStrat;i<=inEnd;i++){ if (inorder[i] == rootVal){ index = i; break; } } TreeNode root = new TreeNode(rootVal); int leftSize = index-inStrat; root.left = build(preorder, preStrat+1,preStrat+leftSize, inorder,inStrat,index-1 ); root.right = build(preorder, preStrat+leftSize+1,preEnd, inorder,index+1,inEnd); return root; } }