106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode)

题目描述

给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。

题目示例

输入:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]

输出:[3,9,20,null,null,15,7]

解题思路

参考代码

java 复制代码
class Solution {
    int post_idx;
    int[] postorder;
    int[] inorder;
    Map<Integer, Integer> idx_map = new HashMap<>();

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        this.postorder = postorder;
        this.inorder = inorder;
        // 从后序遍历的最后一个元素开始
        post_idx = postorder.length - 1;
        // 建立 元素 下标 对应的哈希表
        int idx = 0;
        for(Integer val : inorder) {
            idx_map.put(val, idx++);
        }
        return helper(0, inorder.length - 1);
    }

    public TreeNode helper(int in_left, int in_right) {
        // 如果这里没有节点构造二叉树了,就结束
        if(in_left > in_right) {
            return null;
        }
        // 选择post_idx位置的元素作为当前子树根节点
        int root_val = postorder[post_idx];
        TreeNode root = new TreeNode(root_val);
        // 根据root所在位置分成左右两颗子树
        int index = idx_map.get(root_val);
        // 下标减一
        post_idx--;
        // 构造右子树
        root.right = helper(index + 1, in_right);
        // 构造左子树
        root.left = helper(in_left, index - 1);
        return root;
    }
}
相关推荐
数智工坊12 分钟前
【UniT论文阅读】:用统一物理语言打通人类与人形机器人的知识壁垒
论文阅读·人工智能·深度学习·算法·机器人
梓䈑14 分钟前
【算法题攻略】模拟
c++·算法
Evand J16 分钟前
【课题推荐与代码介绍】卡尔曼滤波器正反向估计算法原理与MATLAB实现
开发语言·算法·matlab
DFT计算杂谈20 分钟前
VASP新手入门: IVDW 色散修正参数
linux·运维·服务器·python·算法
吃着火锅x唱着歌35 分钟前
LeetCode 962.最大宽度坡
算法·leetcode·职场和发展
无限进步_1 小时前
【C++】C++11的类功能增强与STL变化
java·前端·数据结构·c++·后端·算法
WL_Aurora1 小时前
Python 算法基础篇之排序算法(一):冒泡、选择、插入
python·算法·排序算法
凌波粒1 小时前
LeetCode--257. 二叉树的所有路径(二叉树)
算法·leetcode·职场和发展
AI算法沐枫1 小时前
大一学生如何入门机器学习,深度学习,学习顺序如何?
人工智能·python·深度学习·学习·线性代数·算法·机器学习
codealy1 小时前
Rust 核心理论: 高并发与异步(三)
算法·rust