题目
给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。
代码
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
int inlen = inorder.length;
int postlen = postorder.length;
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < inlen; i++){
map.put(inorder[i], i);
}
return buildTree(postorder, 0, postlen - 1, map, 0, inlen - 1);
}
private TreeNode buildTree(int[] postorder, int postLeft, int postRight, Map<Integer, Integer> map, int inLeft, int inRight){
if(postLeft > postRight || inLeft > inRight){
return null;
}
int rootVal = postorder[postRight];
TreeNode root = new TreeNode(rootVal);
int postIndex = map.get(rootVal);
root.left = buildTree(postorder, postLeft, postIndex - inLeft + postLeft - 1, map, inLeft, postIndex - 1);
root.right = buildTree(postorder, postIndex - inLeft + postLeft, postRight - 1, map, postIndex + 1,inRight );
return root;
}
}