Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Construct a tree from inorder and postorder

Reconstruct a binary tree from its inorder and postorder traversals and return its preorder traversal.

Python practice25 minTrees & Binary TreesAdvancedLast updated March 29, 2026

Problem statement

You are given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree. All values are unique. Reconstruct the binary tree and return its preorder traversal as a list of integers (root-left-right). Return format: a Python list representing the preorder traversal. Example: [1, 2, 3]. If the tree is empty (both lists empty), return an empty list [].

Task

Given inorder and postorder traversal arrays (with unique values), rebuild the original binary tree and output a list of node values in preorder (root-left-right).

Examples

Example 1

Input

inorder = [9, 3, 15, 20, 7], postorder = [9, 15, 7, 20, 3]

Output

[3, 9, 20, 15, 7]

The reconstructed tree has root 3, left child 9, and right subtree with root 20 and children 15 and 7. Preorder (root-left-right) is [3,9,20,15,7].

Input format

Two lists of integers: inorder and postorder (both have the same length, values are unique). Example call: build_tree([9,3,15,20,7], [9,15,7,20,3])

Output format

A list of integers representing the preorder traversal of the reconstructed tree. Example: [3, 9, 20, 15, 7]

Constraints

0 <= len(inorder) == len(postorder) <= 1000; All integers in inorder and postorder are unique; The inputs always represent a valid binary tree.

Samples

Sample 1

Input

inorder = [2, 1, 3], postorder = [2, 3, 1]

Output

[1, 2, 3]

Reconstructed tree root 1 with left 2 and right 3 -> preorder [1,2,3].