题目描述
给定两个整数数组
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 {private Map<Integer,Integer> indexMap;public TreeNode myBulidTree(int[] preorder, int[] inorder,int pre_left,int pre_right,int in_left,int in_right){if(pre_left>pre_right) return null;int root_pre=pre_left;TreeNode root=new TreeNode(preorder[root_pre]);//int root_in=indexMap.get(preorder[root_pre]);int left_tree_size=root_in-in_left;root.left=myBulidTree(preorder,inorder,pre_left+1,pre_left+left_tree_size,in_left,root_in-1);root.right=myBulidTree(preorder,inorder,pre_left+left_tree_size+1,pre_right,root_in+1,in_right);return root;}public TreeNode buildTree(int[] preorder, int[] inorder) {int n=preorder.length;indexMap=new HashMap<Integer,Integer>();for(int i=0;i<n;i++){indexMap.put(inorder[i],i);}return myBulidTree(preorder,inorder,0,n-1,0,n-1);}
}
参考链接:105. 从前序与中序遍历序列构造二叉树 - 力扣(LeetCode)