力扣 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;
    }
}
相关推荐
bkspiderx22 分钟前
C++中的访问控制:private、public与protected的深度解析
开发语言·c++·算法·访问控制·private·public·protected
ullio1 小时前
arc207c - Combine to Make Non-decreasing
算法
ZhuNian的学习乐园1 小时前
LLM对齐核心:RLHF 从基础到实践全解析
人工智能·python·算法
iAkuya1 小时前
(leetcode)力扣100 31K个一组翻转链表(模拟)
算法·leetcode·链表
铭哥的编程日记2 小时前
二叉树遍历的递归和非递归版本(所有题型)
算法
&永恒的星河&2 小时前
告别过时预测!最新时序新SOTA:TimeFilter教会模型“选择性失明”
人工智能·深度学习·算法·时序预测·timefilter·时序算法
闻缺陷则喜何志丹2 小时前
【二分查找】P9029 [COCI 2022/2023 #1] Čokolade|普及+
c++·算法·二分查找·洛谷
leiming62 小时前
c++ set容器
开发语言·c++·算法
C雨后彩虹2 小时前
猜密码问题
java·数据结构·算法·华为·面试
ullio2 小时前
div1+2. 2180C - XOR-factorization
算法