力扣面试150题-- 从中序与后序遍历序列构造二叉树

Day 44

题目描述

思路

这题类似与昨天那题,首先来复习一下,后序遍历,对于后序遍历每一个元素都满足以下规律:

(左子树)(右子树)(根),那么我们直接修改昨天的代码即可。前序是从前向后找根,后序我们就从后向前找根。

代码如下:

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public Map<Integer,Integer>indexmap;
    public TreeNode findroot(int[]inorder,int[]postorder,int inleft,int inright,int postleft,int postright){
        if(postleft>postright){
            return null;
        }
        int root_num=postorder[postright];//从后向前找根
        int in=indexmap.get(postorder[postright]);//获取根在中序遍历中的序号
        TreeNode root=new TreeNode(root_num);
        root.left=findroot(inorder,postorder,inleft,in-1,postleft,postright-inright+in-1);
        root.right=findroot(inorder,postorder,in+1,inright,postright-inright+in,postright-1);
        return root;
    }
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        indexmap=new HashMap<Integer,Integer>();
        int n=inorder.length;
        for(int i=0;i<n;i++){//存放每个元素在中序遍历中的序号
            indexmap.put(inorder[i],i);
        }
        TreeNode root=findroot(inorder,postorder,0,n-1,0,n-1);
        return root;
    }
}
相关推荐
羊羊小栈1 分钟前
基于「YOLO目标检测 + 多模态AI分析」的公共场所暴力安全智能检测分析预警系统
人工智能·算法·面试·毕业设计·大作业
keke.shengfengpolang9 分钟前
业务数据分析面试SQL真题汇总:从字节面经看高频考点
面试
土星云SaturnCloud11 分钟前
ResNet-50 图像分类算法在边缘微服务器上的部署与性能评测
服务器·人工智能·算法·边缘计算·resnet-50
Niuguangshuo13 分钟前
文本-音频时间戳对齐:5 个开源工具实测
算法·开源·音视频
Niuguangshuo17 分钟前
论文解读:RNN-Transducer,端到端流式 ASR 的骨架
算法·语音识别
GreenTea29 分钟前
🔥别再用压缩了,Codex、NVIDIA、DeepSeek、Uber 给出 Agent 上下文管理的新答案
前端·后端·算法
All for pursuit.42 分钟前
【矩阵-2】240.搜索二维矩阵 II
数据结构·c++·算法·leetcode
艾莉丝努力练剑1 小时前
【AI大模型接入SDK】LLMManager类架构与智能指针选型
网络·c++·人工智能·学习·面试·架构
6Hzlia1 小时前
【Classic 150 刷题计划】 LeetCode 209. 长度最小的子数组 | C++ 滑动窗口(毛毛虫算法)经典模板
c++·算法·leetcode
6Hzlia1 小时前
【Classic 150 刷题计划】 LeetCode 28. 找出字符串中第一个匹配项的下标 | C++ 滑动窗口与子串比对
c++·算法·leetcode