leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal(中序和后序遍历数组中恢复二叉树)

博客介绍了根据中序遍历和后序遍历构建树的思路。中序遍历顺序是左子树、root、右子树,后序遍历是左子树、右子树、root。通过后序遍历最后一个元素确定root,在中序遍历中找到其位置,划分左右子树范围,再递归构建左右子树。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

思路:

我们知道,中序遍历是:左子树,root,右子树,
而后序遍历是:左子树,右子树,root。

所以,后序遍历的最后一个元素是root,
搜索这个root在inorder中的位置,就可以把inorder的左子树,右子树的范围找出来,
利用这个范围(长度),又可以把postorder中的左子树,右子树找出来。

然后递归,再build 左子树和右子树范围的inorder, postorder.

例如,找到root对应的inorder的位置为rootIdx:
因此可以得到inorder中左子树范围:start~ rootIdx -1
右子树子范围:rootIdx + 1 ~ end
进而得到右子树size = end - rootIdx

class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        int n = inorder.length;
        return build(inorder, postorder, 0, n-1, 0, n-1);
    }

    TreeNode build(int[] inorder, int[] postorder, int iS, int iE,
    int pS, int pE) {
        if(iS > iE || pS > pE) return null;

        int rootVal = postorder[pE];
        TreeNode root = new TreeNode(rootVal);

        int rootIdx = iS;
        while(rootIdx <= iE) {
            if(inorder[rootIdx] == rootVal) break;
            rootIdx ++;
        }
        //不能用binarySearch,因为不是排序的
        //int rootIdx = Arrays.binarySearch(inorder, rootVal);
        
        root.left = build(inorder, postorder, iS, rootIdx-1, pS, pS+rootIdx-1-iS);
        root.right = build(inorder, postorder, rootIdx+1, iE, pS+rootIdx-iS, pE-1);
        return root;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值