LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal

LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal (从中序与后序遍历序列构造二叉树)

题目

链接

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

问题描述

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

示例

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

提示

1 <= inorder.length <= 3000
postorder.length == inorder.length
-3000 <= inorder[i], postorder[i] <= 3000
inorder 和 postorder 都由 不同 的值组成
postorder 中每一个值都在 inorder 中
inorder 保证是树的中序遍历
postorder 保证是树的后序遍历

思路

只要有中序遍历,就代表可以确定唯一的二叉树,借助递归来搭建。

复杂度分析

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

代码

Java

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

    public TreeNode build(int[] inorder, int is, int ie, int[] postorder, int ps, int pe) {
        if (is > ie) {
            return null;
        }
        int rootval = postorder[pe];
        int index = -1;
        for (int i = is; i <= ie; i++) {
            if (inorder[i] == rootval) {
                index = i;
                break;
            }
        }
        int size = index - is;
        TreeNode root = new TreeNode(rootval);
        root.left = build(inorder, is, index - 1, postorder, ps, ps + size - 1);
        root.right = build(inorder, index + 1, ie, postorder, ps + size, pe - 1);
        return root;
    }
posted @ 2022-04-09 22:37  cheng102e  阅读(37)  评论(0编辑  收藏  举报