/**
* 剑指 Offer 07. 重建二叉树
* https://leetcode.cn/problems/zhong-jian-er-cha-shu-lcof/
* 思路:前序遍历数组的第一个结点是根结点,在中序遍历数组中找到根结点,根结点左边是是左子树的元素,根结点右边是右子树的元素
* 递归此过程找出所有子树的根结点
* */
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return buildTree(preorder, inorder, 0, 0, preorder.length - 1);
}
private TreeNode buildTree(int[] preorder, int[] inorder, int i, int start, int end) {
if (start > end) {
return null;
}
TreeNode root = new TreeNode(preorder[i]);
for (int j = start; j <= end; j++) {
if (inorder[j] == root.val) {
root.left = buildTree(preorder, inorder, i + 1, start, j - 1);
root.right = buildTree(preorder, inorder, i + j - start + 1, j + 1, end);
}
}
return root;
}
}