889. Construct Binary Tree from Preorder and Postorder Traversal

Created: 10/31/2021

Leetcodearrow-up-right

Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree.

If there exist multiple answers, you can return any of them.

Example 1:

Example 2:

Constraints:

  • 1 <= preorder.length <= 30

  • 1 <= preorder[i] <= preorder.length

  • All the values of preorder are unique.

  • postorder.length == preorder.length

  • 1 <= postorder[i] <= postorder.length

  • All the values of postorder are unique.

  • It is guaranteed that preorder and postorder are the preorder traversal and postorder traversal of the same binary tree.

Basic Idea:

首先我们可以注意到在preorder中每次都是root在最前面,而在postorder中root则会在最后面,利用这个性质我们可以递归地每次将左右子树所对应的array分离出来,然后递归调用求解。

例如对于上图中的例子

Java Code:

Last updated