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;
    }
}
相关推荐
XWalnut3 小时前
LeetCode刷题 day13
数据结构·算法·leetcode
炽烈小老头3 小时前
【每天学习一点算法 2026/04/17】多数元素
数据结构·学习·算法
HY小宝F4 小时前
破局研发管理“双面角色”:从小团队救火走向系统化治理
职场和发展
云泽8084 小时前
第十五届蓝桥杯大赛软件赛省赛C/C++大学B组
c语言·c++·算法·蓝桥杯
大模型最新论文速读4 小时前
VQKV:KV Cache 压缩 82% 性能几乎不降
人工智能·深度学习·算法·机器学习·自然语言处理
yongui478344 小时前
基于MSP430和Zigbee技术的煤矿综合监控系统设计与实现
算法
Ww.xh4 小时前
ESP8266连接AI大模型完整指南
人工智能·算法·语言模型
俺不要写代码4 小时前
lambda表达式理解
c++·算法
澈2074 小时前
动态内存管理:从基础到实战详解
c++·算法
想唱rap5 小时前
C++11之包装器
服务器·开发语言·c++·算法·ubuntu