解题思路:
分治
以中序遍历为参照,用前序遍历的节点构建二叉树。
root + 1 + index - left表示前序遍历右子树的开始节点,即当前节点的下一个节点+左子树长度。
class Solution {int[] preorder;HashMap<Integer, Integer> map = new HashMap<>();public TreeNode buildTree(int[] preorder, int[] inorder) {this.preorder = preorder;for (int i = 0; i < inorder.length; i++) {map.put(inorder[i], i);}return recur(0, 0, inorder.length - 1);}TreeNode recur(int root, int left, int right) {if (left > right) return null;TreeNode node = new TreeNode(preorder[root]);int index = map.get(preorder[root]);node.left = recur(root + 1, left, index - 1);node.right = recur(root + 1 + index - left, index + 1, right);return node;}
}