给定两个整数数组?
preorder
?和?inorder
?,其中?preorder
?是二叉树的先序遍历,?inorder
?是同一棵树的中序遍历,请构造二叉树并返回其根节点。
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
int size = preorder.length;
Map<Integer,Integer> store = new HashMap<>();
for (int i = 0; i < inorder.length; i++){
store.put(inorder[i],i);
}
return build(preorder, store,0,0,size - 1);
}
private TreeNode build(int[] preorder, Map<Integer,Integer> store, int root,int left,int right){
if(left > right){
return null;
}
TreeNode node = new TreeNode(preorder[root]);
int middle = store.get(preorder[root]);
node.left = build(preorder, store,root + 1, left, middle - 1);
//middle - left是左子树的长度 1表示下一个节点
node.right = build(preorder, store,root + middle - left + 1, middle + 1, right);
return node;
}
}