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;
    }
}
相关推荐
艾莉丝努力练剑6 分钟前
【C语言16天强化训练】从基础入门到进阶:Day 6
c语言·数据结构·学习·算法
快去睡觉~1 小时前
力扣1005:k次取反后最大化的数组和
数据结构·算法·leetcode
smilejingwei1 小时前
数据分析编程第二步: 最简单的数据分析尝试
数据库·算法·数据分析·esprocspl
草莓熊Lotso2 小时前
【C语言强化训练16天】--从基础到进阶的蜕变之旅:Day10
c语言·开发语言·经验分享·算法·强化
张同学的IT技术日记2 小时前
详细实例说明+典型案例实现 对迭代法进行全面分析 | C++
算法
Coovally AI模型快速验证2 小时前
全景式综述|多模态目标跟踪全面解析:方法、数据、挑战与未来
人工智能·深度学习·算法·机器学习·计算机视觉·目标跟踪·无人机
草莓熊Lotso3 小时前
【C++】--函数参数传递:传值与传引用的深度解析
c语言·开发语言·c++·其他·算法
不知名。。。。。。。。3 小时前
算法 ----- 链式
算法
网易独家音乐人Mike Zhou3 小时前
【Python】圆柱体内部3D点云仿真及ply文件生成,圆形3D点云检测及拟合算法
stm32·单片机·mcu·物联网·算法·点云·iot
scx201310044 小时前
20250822 组题总结
c++·算法