力扣面试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;
    }
}
相关推荐
问好眼2 分钟前
《算法竞赛进阶指南》0x01 位运算-3.64位整数乘法
c++·算法·位运算·信息学奥赛
yyjtx2 分钟前
DHU上机打卡D31
开发语言·c++·算法
GEO行业研究员2 分钟前
《认知锚定与路径锁死:基于爱搜光年模型的AI决策链条风险放大机制监测》
人工智能·算法·ai搜索优化·geo优化·医疗geo·医疗geo优化
wefg16 分钟前
【算法】单调栈和单调队列
数据结构·算法
岛雨QA13 分钟前
图「Java数据结构与算法学习笔记12」
数据结构·算法
岛雨QA20 分钟前
多路查找树「Java数据结构与算法学习笔记11」
数据结构·算法
_Li.24 分钟前
Simulink - 6DOF (Euler Angles)
人工智能·算法·机器学习·游戏引擎·cocos2d
岛雨QA31 分钟前
树结构实际应用「Java数据结构与算法学习笔记10」
数据结构·算法
zephyr0536 分钟前
DP 从放弃到拿捏:一份持续更新的动态规划题解清单(一)
算法·动态规划
岛雨QA38 分钟前
树结构的基础部分「Java数据结构与算法学习笔记9」
数据结构·算法