一、题目内容

image.png

二、题解

解法1:

思路

前序遍历第一个节点为树的根
中序遍历根的位置将树分为左右子树

  1. 在中序遍历中找到根,得到左子树的长度
  2. 前序遍历切割成 根+左子树,递归
  3. 中序遍历切割成 左子树+根,递归

    代码

    ```java public class Solution { public TreeNode reConstructBinaryTree(int[] preorder, int[] inorder) {

    1. //递归调用的终止条件
    2. if (preorder.length == 0 || inorder.length == 0) {
    3. return null;
    4. }
    5. TreeNode root = new TreeNode(preorder[0]);
    6. //在中序遍历中找根结点位置,进行左右子树的划分
    7. for (int i = 0; i < inorder.length; i++) {
    8. //找到根节点
    9. if (root.val == inorder[i]) {
    10. //i为左子树长度
    11. root.left = reConstructBinaryTree(Arrays.copyOfRange(preorder, 1, i + 1), Arrays.copyOfRange(inorder, 0, i));
    12. root.right = reConstructBinaryTree(Arrays.copyOfRange(preorder, i + 1, preorder.length), Arrays.copyOfRange(inorder, i + 1, inorder.length));
    13. break;
    14. }
    15. }
    16. return root;

    } }

```