当前位置: 首页 > article >正文

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]

解题思路

在这里插入图片描述

在这里插入图片描述

参考代码

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;
    }
}

http://www.kler.cn/news/233376.html

相关文章:

  • RTE2023第九届实时互联网大会:揭秘未来互联网趋势,PPT分享引领行业新思考
  • Python基础篇_修饰符(Decorators)【下】
  • 常用的正则表达式
  • 一条 SQL 查询语句是如何执行的
  • 探索Spring Validation:优雅实现后端数据验证的艺术
  • 数据结构-->线性表-->单链表
  • JAVA面试题12
  • 信号——block+pending+handler表
  • C语言常见面试题:什么是常量?C语言中有哪些类型的常量?
  • Python 小白的 Leetcode Daily Challenge 刷题计划 - 20240209(除夕)
  • 初识文件包含漏洞
  • 【OpenHarmony硬件操作】风扇与温湿度模块
  • 【Spring】Spring 对 Ioc 的实现
  • kaggle实战语义分割-Car segmentation(附源码)
  • 数据库管理phpmyadmin
  • Linux C/C++ 原始套接字:打造链路层ping实现
  • 【ESLint】TypeError:this.libOptions.parse is not a function
  • 【从Python基础到深度学习】4. Linux 常用命令
  • MinMaxScaler, StandardScaler数据预处理中常用的两种缩放方法,用于将数据标准化或归一化到特定的范围或分布
  • 【CV论文精读】EarlyBird: Early-Fusion for Multi-View Tracking in the Bird’s Eye View
  • IOS破解软件安装教程
  • 达梦数据库适配Springboot+MybatisPlus+达梦数据库
  • 谷歌 DeepMind 联合斯坦福推出了主从式遥操作双臂机器人系统增强版ALOHA 2
  • 嵌入式单片机中晶振的工作原理
  • laravel distinct查询问题,laravel子查询写法
  • FastAdmin西陆房产系统(xiluHouse)全开源
  • 百面嵌入式专栏(面试题)内存管理相关面试题1.0
  • WebSocket 通信流程,注解和Spring实现WebSocket ,实战多人聊天室系统
  • ChatGPT高效提问—prompt常见用法(续篇五)
  • Flask 入门8:Web 表单