DSA SectionMedium

Tree Construction

Detailed guide and Python implementation for the 'Tree Construction' problem.

Problem Statement

Medium

Write a function build_tree(preorder, inorder) that reconstructs a binary tree from its preorder and inorder traversal lists and returns the level-order traversal of the reconstructed tree (represented as a list, with None for empty nodes).

Constraints
  • 1 <= len(preorder) <= 1000
  • inorder.length == preorder.length

Examples

Example 1
Input
preorder = [3, 9, 20, 15, 7], inorder = [9, 3, 15, 20, 7]
Output
[3, 9, 20, None, None, 15, 7]
Explanation

Preorder allows identifying the root 3. Inorder splits left subtree [9] and right subtree [15, 20, 7]. Reconstructed tree has level order [3, 9, 20, None, None, 15, 7].

Need a Hint?
Consider using Trees-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.