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;
    }
}
相关推荐
爱编程的鱼几秒前
想学编程作为今后的工作技能,学哪种语言适用性更强?
开发语言·算法·c#·bug
yq146828609018 分钟前
C (统计二进制中“1“的个数)
c语言·开发语言·算法
程序员三藏22 分钟前
接口自动化测试框架搭建详解
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
被AI抢饭碗的人25 分钟前
算法题(254):灾后重建
算法·leetcode·职场和发展
深度学习机器32 分钟前
RAG的另一种思路,基于文档树结构的推理型检索
人工智能·算法·架构
深度学习机器40 分钟前
Agent架构新方向?Claude Skills工作原理解析
人工智能·算法·架构
蓝色汪洋1 小时前
最近联系人-有点疑惑
算法
音符犹如代码2 小时前
ArrayList常见面试题二
java·开发语言·面试·职场和发展
CoovallyAIHub2 小时前
告别碎片化!Dinomaly2:一个极简框架统一所有异常检测任务
深度学习·算法·计算机视觉
Watermelo6172 小时前
从vw/h到clamp(),前端响应式设计的痛点与进化
前端·javascript·css·算法·css3·用户界面·用户体验