Leetcode 从中序与后序遍历序列构造二叉树

java 递归实现

java 复制代码
class Solution {
    private HashMap<Integer, Integer> inorderIndexMap;
    private int postorderIndex;

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        inorderIndexMap = new HashMap<>();
        postorderIndex = postorder.length - 1;

        for(int i = 0; i < inorder.length; i++) {
            inorderIndexMap.put(inorder[i], i);
        }

        return Helper(postorder, 0, inorder.length - 1);
    }

    private TreeNode Helper(int[] postorder, int inorderStart, int inorderEnd) {
        if(inorderStart > inorderEnd) return null;
        //首先确定根节点的值
        int rootValue = postorder[postorderIndex--];
        TreeNode root = new TreeNode(rootValue);

        //获取根节点在中序遍历中的索引,用于后面划分左右子树
        int inorderIndex = inorderIndexMap.get(rootValue);

        // 递归构建右子树和左子树
        // 注意:需要先构建右子树,因为后序遍历的顺序是左右根
        root.right = Helper(postorder, inorderIndex + 1, inorderEnd);
        root.left = Helper(postorder, inorderStart, inorderIndex - 1);

        return root;
    }
}
相关推荐
招聘风控观察10 小时前
招聘质量管理是什么?招聘质量的定义与评价口径完整解释
职场和发展
徐小夕10 小时前
花了3个月,我们做了一款 AI 版的“飞书文档”
前端·算法·github
Robert--cao10 小时前
移动底盘与机械臂联合规划:开源算法与工程实现
算法
小豆庄11 小时前
Mac 上给视频人脸打码:本地工具的依赖、追踪与推理管线
算法·视觉检测·视频·敏捷流程·纹理贴图
星夜离尘5611 小时前
MATLAB 工程实验:从相邻块均值手写重叠 Allan 偏差,数清有效项
算法·matlab·均值算法
y1su14 小时前
Leetcode 字符串模板
java·数据结构·算法·leetcode·职场和发展·动态规划
residual_fan14 小时前
船用柴油机动态机动工况故障诊断:控制感知仿射网络(CAAN)的技术实现
人工智能·算法·数据挖掘·数据分析
其实防守也摸鱼15 小时前
Cylab在线靶场——CTF中的通用技能
linux·数据库·学习·算法·靶场·ctf·学习网络安全
蓝悦无人机15 小时前
《Planning algorithms》读书笔记——第8章 反馈运动规划
算法·读书笔记·反馈运动规划
RaaS10015 小时前
Agent Skills 进了 Linux Foundation:2.8 亿次安装,但装 skill 还没有安全规范
人工智能·算法·架构