一、题目
给出两个整数数组,前序遍历preorder和中序遍历inorder,请构造二叉树并返回根节点。

二、思路
1、前序遍历:根左右,第一个元素就是根节点,中序遍历,左根右,根节点左边左子树,右边右子树。
2、遍历中序遍历的数组,记录下值对应的index,便于寻找根节点的索引。
前序遍历数组的第一个值为根节点,找到根节点在中序遍历数组中的索引位置,分别通过左右子树在前序遍历和中序遍历的索引范围构建左子树和右子树。
递归的种植条件是,前序遍历的左边界>右边界。
三、代码
java
class Solution {
HashMap<Integer,Integer> map = new HashMap<>();
public TreeNode buildTree(int[] preorder, int[] inorder) {
for(int i = 0;i<inorder.length;i++){
map.put(inorder[i],i);
}
return build(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
}
public TreeNode build(int[] preorder,int preStartIndex,int preEndIndex,int[] inorder,int inStartIndex,int inEndIndex){
if(preStartIndex > preEndIndex || inStartIndex > inEndIndex) return null;
int index = map.get(preorder[preStartIndex]);
int leftSize = index - inStartIndex;
TreeNode root = new TreeNode();
root.val = inorder[index];
root.left = build(preorder,preStartIndex+1,preStartIndex+leftSize,inorder,inStartIndex,index-1);
root.right = build(preorder,preStartIndex+leftSize+1,preEndIndex,inorder,index+1,inEndIndex);
return root;
}
}
