
class Solution {
Map map=new HashMap<>();
int post_idx;
int[] inorder,postorder;
public TreeNode buildTree(int[] inorder, int[] postorder) {
this.inorder=inorder;
this.postorder=postorder;
//在接下来的helper方法中用于按顺序从右向左获取后序序列中的值
//也在接下来的for循环中充当中序序列值的索引
post_idx=-1;
//为中序序列添加映射,以便在接下来用于通过val得到其在中序序列的索引下标
for(Integer val:inorder){
post_idx++;
map.put(val,post_idx);
}
return helper(0,post_idx);
}
public TreeNode helper(int left,int right){
//[left,right]是一个作用于中序序列的下标区间,该区间表示一棵树
//该区间内一定有一个节点是该树的根节点
//当left>right表示不存在该树。返回null
if(left>right){
return null;
}
//获取后序序列中的索引下标为post_idx的值
int val=this.postorder[post_idx];
//创建节点
TreeNode root=new TreeNode(val);
//通过val获取该节点在中序序列的位置
int idx=map.get(val);
post_idx--;
//idx是我们获得的在中序序列的索引下标,它的右边即为右子树,左边即为左子树
root.right=helper(idx+1,right);
root.left=helper(left,idx-1);
return root;
}
}
图解注意:在【中序、后序遍历序列】构造二叉树时,需先构造右子树,这是由于后序序列的特性决定的,后序序列:左右根。也就是说当从右往左获取值的时候,先获取的是根,然后是右子树,最后才是左子树。
中序:2143
后序:2431