1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public class Solution { public TreeNode reConstructBinaryTree(int [] pre,int [] in) { if(pre==null||in==null) { return null; } return reConstructTree(pre,0,pre.length-1,in,0,in.length-1); } public TreeNode reConstructTree(int[] pre, int startPre, int endPre, int[] in, int startIn, int endIn) { if(startPre>endPre|startIn>endIn) { return null; } int rootValue = pre[0]; TreeNode root=new TreeNode(rootValue); root.left=null; root.right=null; int indexIn=0; for(int i=startIn;i<=endIn;i++) { if(in[i]==rootValue) { indexIn=i; break; } } int leftLength= indexIn-startIn; int leftPreEnd=startPre+leftLength; root.left=reConstructTree(pre,startPre+1,leftPreEnd,in,startIn,indexIn-1); root.right=reConstructTree(pre,leftPreEnd+1,endPre,in,indexIn+1,endIn); return root; }
|