重建二叉树
输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
示例 1:
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
示例 2:
Input: preorder = [-1], inorder = [-1] Output: [-1]
思路:递归创建树木,要注意前序遍历和中序遍历左右子树的区间
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private Map<Integer,Integer> indexMap;
public TreeNode mybuildTree(int[] preorder,int[] inorder,int pre_left,int pre_right,int in_left,int in_right){
if(pre_left>pre_right){
return null;
}
int pre_root = pre_left;
int in_root = indexMap.get(preorder[pre_root]);
TreeNode root = new TreeNode(preorder[pre_root]);
int size_left = in_root-in_left;
root.left=mybuildTree(preorder,inorder,pre_left+1,pre_left+size_left,in_left,in_root-1);
root.right=mybuildTree(preorder,inorder,pre_root+size_left+1,pre_right,in_root+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 mybuildTree(preorder,inorder,0,n-1,0,n-1);
}
}