⭐北邮复试刷题106. 从中序与后序遍历序列构造二叉树__递归分治 (力扣每日一题)

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

给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。

示例 1:

输入:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]

输出:[3,9,20,null,null,15,7]
示例 2:

输入:inorder = [-1], postorder = [-1]

输出:[-1]
提示:

1 <= inorder.length <= 3000

postorder.length == inorder.length

-3000 <= inorder[i], postorder[i] <= 3000

inorder 和 postorder 都由 不同 的值组成

postorder 中每一个值都在 inorder 中

inorder 保证是树的中序遍历

postorder 保证是树的后序遍历

题解:

同2月20日每日一题,使用递归分治,对每个子树的中序和后序序列分别处理即可,具体思路可见北邮复试刷题105. 从前序与中序遍历序列构造二叉树__递归分治 (力扣每日一题)

代码:

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

        return myBuildTree(inorder,postorder,0,inorder.length-1,0,postorder.length-1);
    }

    public TreeNode myBuildTree(int[] inorder,int[] postorder,int inStart,int inEnd,
        int postStart,int postEnd){
        // 递归边界,因某子树中序序列与后序序列长度相同 故选择一种判断即可
        if(inStart > inEnd){
            return null;
        }

        TreeNode res = new TreeNode(postorder[postEnd]);
        int post_in_inorder = map.get(postorder[postEnd]);
        int placeLeft = post_in_inorder-1 - inStart;
        res.left = myBuildTree(inorder,postorder,inStart,post_in_inorder-1,postStart,placeLeft+postStart);
        int placeRight = inEnd - (post_in_inorder+1);
        res.right = myBuildTree(inorder,postorder,post_in_inorder+1,inEnd,postEnd-1-placeRight,postEnd-1);

        return res;
    }
}

结果:

相关推荐
呆呆的小鳄鱼6 分钟前
leetcode:冗余连接 II[并查集检查环][节点入度]
算法·leetcode·职场和发展
墨染点香6 分钟前
LeetCode Hot100【6. Z 字形变换】
java·算法·leetcode
沧澜sincerely7 分钟前
排序【各种题型+对应LeetCode习题练习】
算法·leetcode·排序算法
CQ_07127 分钟前
自学力扣:最长连续序列
数据结构·算法·leetcode
弥彦_23 分钟前
cf1925B&C
数据结构·算法
ldj202029 分钟前
SpringBoot为什么使用new RuntimeException() 来获取调用栈?
java·spring boot·后端
超龄超能程序猿30 分钟前
Spring 应用中 Swagger 2.0 迁移 OpenAPI 3.0 详解:配置、注解与实践
java·spring boot·后端·spring·spring cloud
风象南42 分钟前
SpringBoot配置属性热更新的轻量级实现
java·spring boot·后端
洛阳泰山43 分钟前
Spring Boot 整合 Nacos 实战教程:服务注册发现与配置中心详解
java·spring boot·后端·nacos
Y40900143 分钟前
C语言转Java语言,相同与相异之处
java·c语言·开发语言·笔记