Skills101
← All coding problems

Construct Binary Tree from Preorder and Inorder

mediumTrees+20 XPTime limit 2s

You are given the preorder (node, left, right) and inorder (left, node, right) traversals of a binary tree with distinct values. Rebuild the tree and print it in level order.

Input:

  • line 1: n — the number of nodes
  • line 2: the preorder sequence
  • line 3: the inorder sequence

Output: the tree in level order (top to bottom, left to right) with null for a missing child, trailing nulls left out — e.g. 3 9 20 null null 15 7.

Constraints: 1 ≤ n ≤ 10⁴, distinct values between −10⁴ and 10⁴. The tree's height is at most 500.

Think about it: the first preorder value is the root. Its position in the inorder sequence splits the rest into left and right subtrees. A hash map from value → inorder index makes each split O(1), so the whole build is O(n).

Sample input 1

5
3 9 20 15 7
9 3 15 20 7

Sample output 1

3 9 20 null null 15 7

Sample input 2

1
-1
-1

Sample output 2

-1

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.