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;
    }
}
相关推荐
小小小小王王王1 分钟前
洛谷-P1886 【模板】单调队列 / 滑动窗口
c++·算法
网络安全-杰克10 分钟前
Jmeter压力测试工具安装与使用
自动化测试·软件测试·测试工具·jmeter·职场和发展
PPPPPaPeR.27 分钟前
光学算法实战:深度解析镜片厚度对前后表面折射/反射的影响(纯Python实现)
开发语言·python·数码相机·算法
看我干嘛!32 分钟前
python第五次作业
算法
历程里程碑37 分钟前
Linux 库
java·linux·运维·服务器·数据结构·c++·算法
Sheep Shaun39 分钟前
如何让一个进程诞生、工作、终止并等待回收?——探索Linux进程控制与Shell的诞生
linux·服务器·数据结构·c++·算法·shell·进程控制
Pluchon40 分钟前
硅基计划4.0 简单模拟实现AVL树&红黑树
java·数据结构·算法
June bug1 小时前
【PMP】敏捷Scrum实践
经验分享·职场和发展·学习方法·scrum
生锈的键盘1 小时前
推荐算法实践:交叉特征的理解
算法
乌萨奇也要立志学C++1 小时前
【洛谷】BFS 求解最短路:从马的遍历到迷宫问题的实战解析
算法·宽度优先