代码拉取完成,页面将自动刷新
import java.util.HashMap;
import java.util.Map;
public class _106 {
static class Solution1{
public TreeNode buildTree(int[] inorder, int[] postorder) {
//核心思想,后序遍历的数组,最后一个元素一定是 root
// 通过 root,找到中序遍历的节点位置,它左侧所有元素为左子树,右侧为右子树。
//通过中序遍历的序列可以计算出左子树和子树的数量。
//然后通过数量调整后序遍历左右子树在postorder上的位置
//不断递归重复上述过程
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0;i < inorder.length;i++){
map.put(inorder[i],i);
}
return build(map,inorder,postorder,0,inorder.length-1,0,postorder.length-1);
}
public TreeNode build(Map<Integer,Integer> map,int[] inorder, int[] postorder,int iL,int iR,int pL,int pR){
if(iL>iR || pL > pR) return null;
TreeNode root = new TreeNode(postorder[pR]);
int i = map.get(root.val);
int leftCount = i - iL;
int rightCount = iR - i;
root.left = build(map,inorder,postorder,iL,i-1,pL,pL+leftCount-1);
root.right = build(map,inorder,postorder,i+1,iR,pR-rightCount,pR-1);
return root;
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。