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;
    }
}
相关推荐
地平线开发者2 小时前
J6B vio scenario sample
算法
Ruihong10 小时前
Vue withDefaults 转 React:VuReact 怎么处理?
vue.js·react.js·面试
kyriewen10 小时前
别再这样写 async/await 了:我在 Code Review 中见过最多的 8 个错误
前端·javascript·面试
BothSavage14 小时前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn14 小时前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法
烬羽16 小时前
字符串算法入门:从反转字符串到回文判断,面试不再慌
算法·面试
云技纵横16 小时前
一个 @Async,把 @Transactional 的事务边界打穿了
后端·面试
想要成为糕糕手16 小时前
Harness Engineering:大模型时代的“马鞍”——从记忆层开始,让AI真正为你所用
面试·ai编程·claude