106.从中序与后序遍历序列构造二叉树
做不出来,这题能用哈希有个条件就是,每个节点的值都不一样。
先根据后序遍历找到根结点,在根据根结点的数组下标,把中序遍历序列分成2部分,就这样递归不断地分,直到左子树,右子树的数组边界范围出现左边界大于右边界。开始回归上一层函数。
其实看代码还是很不好理解的,得自己动动脑筋去模拟才行,光看代码就是脑子想动也动不起来,主要我还是经常对着代码半发呆半想,直到想睡觉,效率很低。
class Solution {
HashMap
mp=new HashMap<>(); public TreeNode buildTree(int[] inorder, int[] postorder) {
for(int i=0;i
mp.put(inorder[i],i);
}
return build(0,inorder.length-1,0,postorder.length-1,postorder);
}
TreeNode build(int il,int ir,int pl,int pr,int[] postorder){//找到当前的根节点
//参数是左子树的左子树的左右数组范围,右子树的左右数组范围
if(il>ir||pl>pr)
return null;
int root=postorder[pr];
int center=mp.get(root);
TreeNode node=new TreeNode(root);
node.left=build(il,center-1,pl,pl-il+center-1,postorder);//找到左子树的根节点
node.right=build(center+1,ir,pl+center-il,pr-1,postorder);//找右子树的根节点
return node;
}
}