Construct Binary Tree from Preorder and Inorder

Practice this coding question on Coding Gurukul.

Problem statement

A monitoring service saved two traversal logs of a binary device hierarchy but lost the links between devices. Unique device identifiers allow the hierarchy to be reconstructed. Your task Construct the binary tree described by its preorder and inorder traversals. Important details Preorder visits a node before its left and right subtrees. Inorder visits the left subtree, then the node, then the right subtree. Every identifier is distinct and the two logs describe the same valid tree, so the result is unique. Preserve left and right child positions when printing; missing children inside the serialization cannot be skipped. Worked example Preorder 8 3 10 and inorder 3 8 10 put 8 at the root, 3 on its left and 10 on its right. The breadth-first output is 8 3 10.

Input format

First line: n. Second line: n preorder values. Third line: n inorder values.

Output format

Print the tree in breadth-first order, with null for missing children. Process left before right, enqueue children only for real nodes, and omit trailing null tokens.

Constraints

1 <= n <= 1000; -3000 <= values <= 3000; values are distinct and traversals are consistent.

Sample input

3
8 3 10
3 8 10

Sample output

8 3 10

Sign in to run or submit a solution in C++, Java or Python.

Loading Coding Gurukul…