其他分享
首页 > 其他分享> > LeetCode 889. Construct Binary Tree from Preorder and Postorder Traversal

LeetCode 889. Construct Binary Tree from Preorder and Postorder Traversal

作者:互联网

LeetCode 889. Construct Binary Tree from Preorder and Postorder Traversal (根据前序和后序遍历构造二叉树)

题目

链接

https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/

问题描述

给定两个整数数组,preorder 和 postorder ,其中 preorder 是一个具有 无重复 值的二叉树的前序遍历,postorder 是同一棵树的后序遍历,重构并返回二叉树。

如果存在多个答案,您可以返回其中 任何 一个。

示例

输入:preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]
输出:[1,2,3,4,5,6,7]

提示

1 <= preorder.length <= 30
1 <= preorder[i] <= preorder.length
preorder 中所有值都 不同
postorder.length == preorder.length
1 <= postorder[i] <= postorder.length
postorder 中所有值都 不同
保证 preorder 和 postorder 是同一棵二叉树的前序遍历和后序遍历

思路

由于这无法确定唯一的一颗二叉树,所以我们假设排除根节点后,左边第一个节点是左子树的根节点,然后进行递归操作。

复杂度分析

时间复杂度 O(n^2)
空间复杂度 O(n^2)

代码

Java

    public TreeNode constructFromPrePost(int[] preorder, int[] postorder) {
        int n = postorder.length;
        if (n == 0) {
            return null;
        }
        TreeNode root = build(preorder, 0, n - 1, postorder, 0, n - 1);
        return root;
    }

    public TreeNode build(int[] preorder, int pres, int pree, int[] postorder, int posts, int poste) {
        if (pres > pree) {
            return null;
        }
        if (pres == pree) {
            return new TreeNode(preorder[pres]);
        }
        int rootval = preorder[pres];
        int leftval = preorder[pres + 1];
        int index = -1;
        for (int i = posts; i <= poste; i++) {
            if (postorder[i] == leftval) {
                index = i;
                break;
            }
        }
        int size = index - posts + 1;

        TreeNode root = new TreeNode(rootval);
        root.left = build(preorder, pres + 1, pres + size,
                postorder, posts, index);
        root.right = build(preorder, pres + size + 1, pree,
                postorder, index + 1, poste - 1);

        return root;
    }

标签:Binary,遍历,Preorder,preorder,int,889,二叉树,pres,postorder
来源: https://www.cnblogs.com/blogxjc/p/16124025.html