import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param preOrder int整型一维数组 * @param vinOrder int整型一维数组 * @return TreeNode类 */ public TreeNode reConstructBinaryTree (int[] preOrder, int[] vinOrder) { // write code here if (preOrder.length == 0 || vinOrder.length == 0)return null; TreeNode root = new TreeNode(preOrder[0]); for (int i = 0; i < vinOrder.length; i++) { if (vinOrder[i] == preOrder[0]) { int[] leftPre = new int[i]; System.arraycopy(preOrder, 1, leftPre, 0, i); int[] rightPre = new int[preOrder.length - i - 1]; System.arraycopy(preOrder, 1 + i, rightPre, 0, rightPre.length); int[] leftVin = new int[i]; System.arraycopy(vinOrder, 0, leftVin, 0, i); int[] rightVin = new int[vinOrder.length - i - 1]; System.arraycopy(vinOrder, 1 + i, rightVin, 0, rightVin.length); root.left = reConstructBinaryTree(leftPre, leftVin); root.right = reConstructBinaryTree(rightPre, rightVin); break; } } return root; } }
使用递归,分别构建左右子树