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;
    }
}
相关推荐
To_OC42 分钟前
LC 51 N 皇后:我以为难的是回溯,结果栽在了对角线下标
javascript·算法·leetcode
2401_841495641 小时前
【操作系统】进程同步与互斥实验报告
c++·算法·操作系统·进程·并发·同步·互斥
触底反弹2 小时前
🔥 2026 大模型选择指南:别再只看 Benchmark 了,这些维度才是关键!
人工智能·面试
醇氧4 小时前
CountDownLatch / CyclicBarrier / Semaphore 面试高频问答清单
前端·面试·职场和发展
爱刷碗的苏泓舒5 小时前
PPP-AR 中的参考星选取:数学原理、评价指标与切换处理
算法·gnss·模糊度固定·ppp-ar·星间单差·参考星·卫星端偏差
黄敬峰7 小时前
从零搞懂 useState 与 Fragment:React 函数式组件的基石
面试
烬羽8 小时前
递归老写崩?一个"退回"公式,把回溯题变成填空题
javascript·深度学习·算法
闪电悠米8 小时前
力扣hot100-41.缺失的第一个正数-原地哈希详解
数据结构·算法·哈希算法
星空露珠9 小时前
28种颜色对应名称,
开发语言·数据库·算法·游戏·lua