⚡Flashcard Drill➔
NeetCode #446LC-889MediumTrees
← Back to All Problems

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

📌 Problem Statement & Constraints

Given two integer arrays preorder and postorder representing the pre-order and post-order traversal of a binary tree, construct and return the tree. If multiple trees are valid, return any of them. All values are distinct. Constraints: 1 <= preorder.length <= 30, preorder.length == postorder.length.

💡 Core Algorithmic Approaches

  1. The first element of the pre-order and the last of the post-order are both the root.
  2. The element after the root in the pre-order is the root of the left subtree (assuming a left child exists); its position in the post-order tells you the left subtree's size.
  3. Unlike the pre-order + in-order case, this pair of traversals does not uniquely determine the tree -- but any consistent reconstruction is accepted.
  4. So always assume a left child when both subtrees are non-empty, which yields one valid answer.

💻 Benchmark Python3 Implementation

class Solution:
    def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        idx = {v: i for i, v in enumerate(postorder)}   # O(1) split lookup

        def build(pre_lo: int, pre_hi: int, post_lo: int, post_hi: int) -> Optional[TreeNode]:
            if pre_lo > pre_hi:
                return None
            root = TreeNode(preorder[pre_lo])
            if pre_lo == pre_hi:
                return root                # single node
            left_root = preorder[pre_lo + 1]
            left_size = idx[left_root] - post_lo + 1
            root.left = build(pre_lo + 1, pre_lo + left_size, post_lo, post_lo + left_size - 1)
            root.right = build(pre_lo + left_size + 1, pre_hi, post_lo + left_size, post_hi - 1)
            return root

        return build(0, len(preorder) - 1, 0, len(postorder) - 1)

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): each node is created once with O(1) split lookups.
💾 Space Complexity
O(n) for the index map plus O(h) for the recursion.

⚠️ Interview Pitfalls & Follow-ups

  • Expecting a unique answer: the traversals are ambiguous for single-child nodes, so several trees are valid.
  • Forgetting the pre_lo == pre_hi base case: without it, preorder[pre_lo + 1] would be out of range.
  • Computing left_size incorrectly: it is idx[left_root] - post_lo + 1, the size of the left subtree in the post-order array.
  • Assuming the tree is full: it need not be, hence the ambiguity.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Trees Problems

中文速览与面试要点

根据前序和后序遍历构造二叉树

给定两个整数数组,preorder 和 postorder,其中 preorder 是一个具有 无重复 值的二叉树的前序遍历,postorder 是同一棵树的后序遍历,重构并返回二叉树。如果存在多个答案,您可以返回其中 任何一个 。约束:1 ≤ preorder.length ≤ 30;1 ≤ preorder[i], postorder[i] ≤ preorder.length;preorder 和 postorder 中所有值都 不同 ;每个数组中的值满足 1 ≤ preorder[i], postorder[i] ≤ preorder.length;preorder 保证是二叉树的先序遍历;postorder 保证是二叉树的后序遍历。

核心要点

  • 递归划分(标准解) :前序的第一个元素是根;前序的 第二个 元素是左子树的根,在后续中找到它的位置即可确定左子树的大小。
  • 左子树大小的推导 :设 postorder 中 preorder[pl+1] 的下标为 k,则左子树大小为 k − post_l + 1 。
  • 为什么结果可能不唯一 :前序 + 后序无法唯一确定二叉树(当一个节点只有一个孩子时,无法判断是左还是右)。本解约定「视为左孩子」,是合法答案之一。
  • 复杂度 :O(n) 时间(配合哈希表定位)、O(n) 空间。

常见陷阱

  • 忘记 pre_l == pre_r 的终止条件 : preorder[pre_l + 1] 会越界。
  • 左子树大小算错 : left_size = left_root_post − post_l + 1 ,不是 left_root_post − post_l 。
  • 右子树的后序区间写成 [left_root_post, post_r] :应排除左子树与根,即 [left_root_post + 1, post_r − 1] 。
  • 以为结果唯一 :前序 + 后序不能唯一确定二叉树,题目允许多解。

参考实现

class Solution:
    def constructFromPrePost(self, preorder: list[int], postorder: list[int]) -> 'TreeNode':
        idx = {v: i for i, v in enumerate(postorder)}    # 值 -> 后序下标

        def build(pre_l: int, pre_r: int, post_l: int, post_r: int):
            if pre_l > pre_r:
                return None
            root = TreeNode(preorder[pre_l])            # 前序第一个是根
            if pre_l == pre_r:
                return root                             # 只剩一个节点
            # 前序第二个是左子树的根,它在后序中的位置决定左子树大小
            left_root_post = idx[preorder[pre_l + 1]]
            left_size = left_root_post - post_l + 1
            root.left = build(pre_l + 1, pre_l + left_size, post_l, left_root_post)
            root.right = build(pre_l + left_size + 1, pre_r, left_root_post + 1, post_r - 1)
            return root

        return build(0, len(preorder) - 1, 0, len(postorder) - 1)