105. 从前序与中序遍历序列构造二叉树
给定两个整数数组 preorder
和 inorder
,其中 preorder
是二叉树的先序遍历, inorder
是同一棵树的中序遍历,请构造二叉树并返回其根节点。
示例 1:
输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] 输出: [3,9,20,null,null,15,7]
示例 2:
输入: preorder = [-1], inorder = [-1] 输出: [-1]
提示:
1 <= preorder.length <= 3000
inorder.length == preorder.length
-3000 <= preorder[i], inorder[i] <= 3000
preorder
和inorder
均 无重复 元素inorder
均出现在preorder
preorder
保证 为二叉树的前序遍历序列inorder
保证 为二叉树的中序遍历序列
解法思路:
递归
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {// Recursion// Time: O(n)// Space: O(n)private Map<Integer, Integer> indexMap;public TreeNode buildTree(int[] preorder, int[] inorder) {// 使用 Map 存储中序遍历数组中每个节点值对应的索引,以便快速查找indexMap = new HashMap<>();for (int i = 0; i < inorder.length; i++) {indexMap.put(inorder[i], i);}return buildTreeHelper(preorder, inorder, 0, 0, inorder.length - 1);}private TreeNode buildTreeHelper(int[] preorder, int[] inorder, int preStart, int inStart, int inEnd) {// 递归终止条件:先序遍历数组为空或中序遍历数组的范围越界if (preStart > preorder.length - 1 || inStart > inEnd) {return null;}// 当前子树的根节点值为先序遍历数组的第一个元素int rootVal = preorder[preStart];TreeNode root = new TreeNode(rootVal);// 在中序遍历数组中找到根节点值的索引int inIndex = indexMap.get(rootVal);// 递归构建左右子树root.left = buildTreeHelper(preorder, inorder, preStart + 1, inStart, inIndex - 1);root.right = buildTreeHelper(preorder, inorder, preStart + inIndex - inStart + 1, inIndex + 1, inEnd);return root;}
}