力扣 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;
    }
}
相关推荐
一个不知名程序员www16 小时前
算法学习入门 --- 哈希表和unordered_map、unordered_set(C++)
c++·算法
Sarvartha16 小时前
C++ STL 栈的便捷使用
c++·算法
夏鹏今天学习了吗17 小时前
【LeetCode热题100(92/100)】多数元素
算法·leetcode·职场和发展
飞Link17 小时前
深度解析 MSER 最大稳定极值区域算法
人工智能·opencv·算法·计算机视觉
bubiyoushang88817 小时前
基于CLEAN算法的杂波抑制Matlab仿真实现
数据结构·算法·matlab
曾经的三心草17 小时前
redis-2-数据结构内部编码-单线程-String命令
数据结构·数据库·redis
2401_8948281218 小时前
从原理到实战:随机森林算法全解析(附 Python 完整代码)
开发语言·python·算法·随机森林
Remember_99318 小时前
【LeetCode精选算法】前缀和专题二
算法·哈希算法·散列表
源代码•宸18 小时前
Leetcode—509. 斐波那契数【简单】
经验分享·算法·leetcode·面试·golang·记忆化搜索·动规
博大世界19 小时前
matlab结构体数组定义
数据结构·算法