力扣面试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;
    }
}
相关推荐
天天摸鱼的java工程师7 分钟前
当我成为面试官,我才知道当年那些面试官其实并不是在难为我,而是在考察我面对问题的拆解能力
前端·后端·面试
大熊猫侯佩41 分钟前
Swift 数学计算:用 Accelerate 框架让性能“加速吃鸡”
算法·swift
杰克尼1 小时前
2. 两数相加
算法
Dubhehug1 小时前
4.B树和B+树的区别?为什么MySQL选择B+树作为索引?
数据库·b树·mysql·面试·b+树
无聊的小坏坏1 小时前
单调栈通关指南:从力扣 84 到力扣 42
c++·算法·leetcode
何遇er1 小时前
大厂的前端面试——低代码混合
低代码·面试
_Coin_-1 小时前
算法训练营DAY29 第八章 贪心算法 part02
算法·贪心算法
前端小巷子1 小时前
Cookie与Session:Web开发中的身份验证与数据存储
前端·javascript·面试
阿维同学1 小时前
自动驾驶关键算法深度研究
人工智能·算法·自动驾驶
汪子熙1 小时前
Visual Studio Code 中排除指定文件夹搜索的最佳实践与实现原理
后端·面试