善用Java的工具类
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * } */ public class Solution { /** * * @param preorder int整型一维数组 * @param inorder int整型一维数组 * @return TreeNode类 */ public TreeNode buildTree (int[] preorder, int[] inorder) { // write code here if(preorder.length==0||inorder.length==0) return null; TreeNode root = new TreeNode(preorder[0]); int mid = 0; for(int i = 0 ; i < inorder.length ; i++){ if(inorder[i]== preorder[0]) mid = i; } root.left = buildTree(Arrays.copyOfRange(preorder,1,mid + 1),Arrays.copyOfRange(inorder,0,mid)); root.right = buildTree(Arrays.copyOfRange(preorder,mid + 1,preorder.length),Arrays.copyOfRange(inorder,mid + 1,inorder.length)); return root; } }