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;
    }
}
相关推荐
浊酒南街3 小时前
XGBClassifiler函数介绍
算法·机器学习·xgb
mlxg999993 小时前
hom_mat2d_to_affine_par 的c#实现
算法·计算机视觉·c#
真就死难7 小时前
完全日期(日期枚举问题)--- 数学性质题型
算法·日期枚举
不知道取啥耶8 小时前
C++ 滑动窗口
数据结构·c++·算法·leetcode
花间流风8 小时前
晏殊几何学讲义
算法·矩阵·几何学·情感分析
@心都8 小时前
机器学习数学基础:42.AMOS 结构方程模型(SEM)分析的系统流程
人工智能·算法·机器学习
我想吃烤肉肉9 小时前
leetcode-sql数据库面试题冲刺(高频SQL五十题)
数据库·sql·leetcode
北顾南栀倾寒11 小时前
[算法笔记]cin和getline的并用、如何区分两个数据对、C++中std::tuple类
笔记·算法
一只大侠12 小时前
牛客周赛A:84:JAVA
算法
豆豆酱12 小时前
Informer方法论详解
算法