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
| public class Test {
public TreeNode buildTree(int[] preorder, int[] inorder) {
int len = preorder.length; if (len == 0) { return null; }
int rootVal = preorder[0]; int rootIndex = 0; for (int i = 0; i < len; i++) { if (inorder[i] == rootVal) { rootIndex = i; } }
TreeNode root = new TreeNode(rootVal); root.left = buildTree(Arrays.copyOfRange(preorder, 1, rootIndex + 1), Arrays.copyOfRange(inorder, 0, rootIndex));
root.right = buildTree(Arrays.copyOfRange(preorder, rootIndex+1, len), Arrays.copyOfRange(inorder, rootIndex+1, len));
return root;
}
public static void main(String[] args) { int[] preorder = {3, 9, 20, 15, 7}; int[] inorder = {9, 3, 15, 20, 7};
Test test = new Test(); TreeNode root = test.buildTree(preorder, inorder);
} }
|