day47(12.28)——leetcode面试经典150

106. 从中序与后序遍历序列构造二叉树

106. 从中序与后序遍历序列构造二叉树

我感觉我的数据结构都要忘光光了

题目:

题解:

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> map = new HashMap<>();
    public int[] postorder;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        for(int i=0;i<inorder.length;i++) {
            map.put(inorder[i], i);
        }
        this.postorder = postorder;
        return recur(0,inorder.length-1,0,postorder.length-1);
    }

    public TreeNode recur(int left, int right, int l,int r) {
        if(left > right || l > r) {
            return null;
        }
        int root = postorder[r];
        int i = map.get(root);

        TreeNode node = new TreeNode(root);
        node.left = recur(left, i-1, l, l+i-1-left);
        node.right = recur(i+1, right, l+i-left, r-1);
        return node;
    }
}
相关推荐
武子康1 小时前
H3-World 为何在加载 LoRA 前,先检查导入的代码?
人工智能·深度学习·算法
时间的拾荒人2 小时前
Redis 入门详解:核心特性、重要文件与全局命令实战
开发语言·redis·面试
秋天的怀念_David2 小时前
算法一千零一夜 · 第二十八夜 注册
java·程序人生·算法
Rain的Java大神之路4 小时前
LeetCode 37 解数独面试攻略:回溯 + 位掩码 + MRV,从暴力到毫秒级求解
java·后端·leetcode
NEFU_Jyj4 小时前
贝尔数(组合数学)
算法
希和20275 小时前
C语言程序设计题|有序数组插入数字冒泡排序
c语言·数据结构·算法
Pniubi5 小时前
力扣73 矩阵置零
算法·leetcode·矩阵
爱敲代码的小黄13 小时前
神经网络入门指南:从 CNN、RNN 到 Attention
人工智能·面试·程序员
布莱克60515 小时前
C++ 中 map 的 insert 与 emplace:key 已存在时会覆盖吗?
开发语言·数据结构·c++·算法·map