DSA Section

Tree Construction

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

問題提起

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).

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

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

解決する準備はできましたか?

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

エディタで開く
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推奨される Python リソース

関連するインタラクティブなチュートリアル、チートシート、コード比較で知識を深めてください。