力扣 LeetCode 106. 从中序与后序遍历序列构造二叉树(Day9:二叉树)

解题思路:

前中后序

给前中和后中都可以确定唯一的一棵二叉树

前中:先前 后中

中后:先中 后后

注意区间,统一左闭右开比较好

终止条件: if (postorderStart == postorderEnd) return null;

java 复制代码
class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (inorder.length == 0 || postorder.length == 0) return null;
        return buildHelper(inorder, 0, inorder.length, postorder, 0, postorder.length);
    }

    public TreeNode buildHelper(int[] inorder, int inorderStart, int inorderEnd, int[] postorder, int postorderStart, int postorderEnd) {
        if (postorderStart == postorderEnd) return null;

        int rootValue = postorder[postorderEnd - 1];
        TreeNode root = new TreeNode(rootValue);
        int middleIndex = 0;
        for (middleIndex = 0; middleIndex < inorderEnd; middleIndex++) {
            if (inorder[middleIndex] == rootValue)
                break;
        }

        int leftInorderStart = inorderStart;
        int leftInorderEnd = middleIndex;
        int rightInorderStart = middleIndex + 1;
        int rightInorderEnd = inorderEnd;

        int leftPostorderStart = postorderStart;
        int leftPostorderEnd = postorderStart + (middleIndex - inorderStart);
        int rightPostorderStart = leftPostorderEnd;
        int rightPostorderEnd = postorderEnd - 1;

        root.left = buildHelper(inorder, leftInorderStart, leftInorderEnd, postorder, leftPostorderStart,leftPostorderEnd);
        root.right = buildHelper(inorder, rightInorderStart, rightInorderEnd, postorder, rightPostorderStart,rightPostorderEnd);
        return root;
    }
}
相关推荐
NAGNIP17 小时前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队18 小时前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja1 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶1 天前
算法 --- 字符串
算法
博笙困了1 天前
AcWing学习——差分
c++·算法
NAGNIP1 天前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP1 天前
大模型微调框架之LLaMA Factory
算法
echoarts1 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Python技术极客1 天前
一款超好用的 Python 交互式可视化工具,强烈推荐~
算法