1 public class Solution {//树 my 2 public TreeNode reConstructBinaryTree(int [] pre,int [] in) { 3 return reConBTreeIndex(pre,0,pre.length-1,in,0,in.length-1); 4 } 5 private TreeNode reConBTreeIndex(int[] pre,int preLeft,int preRight,int[] in,int inLeft,int inRight){ 6 //和1思路完全一样,代码更简洁 7 if(preRight<preLeft||inLeft>inRight){ 8 return null; 9 } 10 else{ 11 //System.out.println(pre[preLeft]+"--"+pre[preRight]+" "+in[inLeft]+"--"+in[inRight]); 12 TreeNode node = new TreeNode(pre[preLeft]); 13 for (int i = inLeft; i <= inRight; i++) { 14 if(in[i]==pre[preLeft]){ 15 node.left = reConBTreeIndex(pre,preLeft+1,i-inLeft+preLeft,in,inLeft,i-1); 16 node.right = reConBTreeIndex(pre,preRight-inRight+i+1,preRight,in,i+1,inRight); 17 } 18 } 19 return node; 20 } 21 } 22 }
原文:https://www.cnblogs.com/zhacai/p/10686480.html