力扣面试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;
    }
}
相关推荐
前端付豪18 小时前
1、震惊!99% 前端都没搞懂的 JavaScript 类型细节
前端·javascript·面试
Java水解18 小时前
JAVA经典面试题附答案(持续更新版)
java·后端·面试
大怪v18 小时前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
洛小豆20 小时前
在Java中,Integer.parseInt和Integer.valueOf有什么区别
java·后端·面试
惯导马工20 小时前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
闰五月1 天前
JavaScript执行上下文详解
面试
骑自行车的码农1 天前
【React用到的一些算法】游标和栈
算法·react.js
Lotzinfly1 天前
8 个经过实战检验的 Promise 奇淫技巧你需要掌握😏😏😏
前端·javascript·面试
知其然亦知其所以然1 天前
MySQL 社招必考题:如何优化查询过程中的数据访问?
后端·mysql·面试
努力的小郑1 天前
从一次分表实践谈起:我们真的需要复杂的分布式ID吗?
分布式·后端·面试