力扣106. 从中序与后序遍历序列构造二叉树

注意不变量为左闭右开区间

class Solution {
Map<Integer, Integer> map;

//inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
public TreeNode buildTree(int[] inorder, int[] postorder) {
    map = new HashMap<>();
    for (int i = 0; i < inorder.length; i++) {// 用map保存中序序列的数值对应位置
        map.put(inorder[i], i);
    }
    return findNode(inorder, 0, inorder.length, postorder, 0, postorder.length);
}

public TreeNode findNode(int[] inorder, int inbegin, int inend, int[] postorder, int postBegin, int postend) {
    if (inbegin >= inend || postBegin >= postend) {//说明不满足左闭右开,数组为空返回null
        return null;
    }
    //第一次调用 根节点3 rootindex=1
    int rootindex = map.get(postorder[postend - 1]);//找到后续遍历根节点的值,在找中序遍历中的位置
    TreeNode treeNode = new TreeNode(inorder[rootindex]);

    //第一次调用 中序做数组长度1-0=1 [9]
    int leftLen = rootindex - inbegin;//保存中序遍历左子树长度,用来确定后续数组的长度
    //左闭右开
    //左序数组需要传中序左数组跟后续左数组
    //其中中序切割时传入inbegin,rootindex(中序遍历此次迭代根节点位置)[0,1)[9]
    //后续遍历根据leftLen左子树长度切割传入 postBegin,postBegin+leftLen[0,1)数组[9]
    treeNode.left = findNode(inorder, inbegin, rootindex, postorder, postBegin, postBegin + leftLen);

    //右序数组传入中序右数组 [15,20,7] rootindex + 1=2,inend=5 后续右数组[15,7,20]postBegin + leftLen=1 ,postend - 1=4(排除最后一个节点)
    treeNode.right = findNode(inorder, rootindex + 1, inend, postorder, postBegin + leftLen, postend - 1);

    return treeNode;
}

}

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值