这道题做得比较顺利,但是效果并不是很好
public TreeNode buildTree(int[] preorder, int[] inorder) { if(preorder.length == 0){ return null; } if(preorder.length == 1){ return new TreeNode(preorder[0]); }else{ int m = 0; TreeNode root = new TreeNode(preorder[0]); for(int i = 0;i<inorder.length;i++){ if(inorder[i] == preorder[0]){ m = i; //在中序遍历中找到根节点的位置 break; } } int[] a = Arrays.copyOfRange(inorder,0,m); int[] b = Arrays.copyOfRange(inorder,m+1,inorder.length); int[] c = Arrays.copyOfRange(preorder,1,1+m); int[] d = Arrays.copyOfRange(preorder,m+1,preorder.length); root.left = buildTree(c,a); root.right = buildTree(d,b); return root; }