首页 > 其他 > 详细

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

时间:2021-03-01 09:25:37      阅读:37      评论:0      收藏:0      [点我收藏+]

技术分享图片

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

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

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

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

  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;
};

技术分享图片 

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

原文:https://www.cnblogs.com/niuyourou/p/14461442.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!