Leetcode 889 根据前序和后序遍历构造二叉树 区间递归

  前序遍历与后续遍历的组合可以构成一个完整的子树区间。

  子树的根节点会在前序遍历中该子树的首位出现,在后续遍历中则会在该子树的末尾出现。

  那么,前序-后序的重合节点所构成的区间,便是以该重合节点为根节点的整棵子树。

  进而考虑该思路是否可以一直递归至边界情况。

  JAVA:

复制代码
public final TreeNode constructFromPrePost(int[] pre, int[] post) {
        int childLen = 0, preLen = pre.length, postLen = post.length;
        if (preLen == 0) return null;
        TreeNode root = new TreeNode(pre[0]);
        if (preLen == 1) return root;
        for (int i = 0; i < postLen; i++) {
            if (post[i] == pre[1]) {
                childLen = i;
                break;
            }
        }
        root.left = constructFromPrePost(
                Arrays.copyOfRange(pre, 1, childLen + 2),
                Arrays.copyOfRange(post, 0, childLen+1)
        );
        root.right = constructFromPrePost(
                Arrays.copyOfRange(pre, childLen + 2, preLen),
                Arrays.copyOfRange(post, childLen + 1, postLen - 1)
        );
        return root;
    }
复制代码

  JS:

复制代码
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {number[]} pre
 * @param {number[]} post
 * @return {TreeNode}
 */
var constructFromPrePost = function (pre, post) {
    let childLen = 0, preLen = pre.length, postLen = post.length;
    if (preLen == 0) return null;
    let root = new TreeNode(pre[0]);
    if (preLen == 1) return root;
    for (let i = 0; i < postLen; i++) {
        if (post[i] == pre[1]) {
            childLen = i;
            break;
        }
    }
    root.left = constructFromPrePost(pre.slice(1, childLen + 2), post.slice(0, childLen + 1));
    root.right = constructFromPrePost(pre.slice(childLen + 2, preLen), post.slice(childLen + 1, postLen - 1));
    return root;
};
复制代码

 

posted @   牛有肉  阅读(142)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
历史上的今天:
2020-03-01 JVM 对 interrupt 信号的响应
点击右上角即可分享
微信分享提示