一、题目内容
二、题解
解法1:
思路
前序遍历第一个节点为树的根
中序遍历根的位置将树分为左右子树
- 在中序遍历中找到根,得到左子树的长度
- 前序遍历切割成 根+左子树,递归
-
代码
```java public class Solution { public TreeNode reConstructBinaryTree(int[] preorder, int[] inorder) {
//递归调用的终止条件if (preorder.length == 0 || inorder.length == 0) {return null;}TreeNode root = new TreeNode(preorder[0]);//在中序遍历中找根结点位置,进行左右子树的划分for (int i = 0; i < inorder.length; i++) {//找到根节点if (root.val == inorder[i]) {//i为左子树长度root.left = reConstructBinaryTree(Arrays.copyOfRange(preorder, 1, i + 1), Arrays.copyOfRange(inorder, 0, i));root.right = reConstructBinaryTree(Arrays.copyOfRange(preorder, i + 1, preorder.length), Arrays.copyOfRange(inorder, i + 1, inorder.length));break;}}return root;
} }
```
