力扣面试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;
    }
}
相关推荐
a努力。4 分钟前
中国电网Java面试被问:RPC序列化的协议升级和向后兼容
java·开发语言·elasticsearch·面试·职场和发展·rpc·jenkins
码农水水11 分钟前
得物Java面试被问:大规模数据的分布式排序和聚合
java·开发语言·spring boot·分布式·面试·php·wpf
HaiLang_IT16 分钟前
基于RepVGG与注意力机制的手写潦草汉字识别算法研究
算法
一起努力啊~18 分钟前
算法刷题--字符串
算法
独断万古他化18 分钟前
【二分算法 深度解析】二段性思维与经典题型全通关
java·算法
啊阿狸不会拉杆22 分钟前
《数字图像处理》第 10 章 - 图像分割
图像处理·人工智能·深度学习·算法·计算机视觉·数字图像处理
早川91923 分钟前
9种常用排序算法总结
数据结构·算法·排序算法
Yupureki35 分钟前
《算法竞赛从入门到国奖》算法基础:入门篇-离散化
c语言·数据结构·c++·算法·visual studio
散峰而望38 分钟前
OJ 题目的做题模式和相关报错情况
java·c语言·数据结构·c++·vscode·算法·visual studio code
Mixtral40 分钟前
2026年面试记录转写工具深度测评:3款工具准确率与效率对比
人工智能·面试·职场和发展·语音识别·语音转文字