Prepin
Log in

Transform a binary tree from a pre-order array into an in-order array.

Approach / Explanation

This question requires you to transform the pre-order traversal of a binary tree into an in-order traversal. Binary trees are a data structure where each node can have a maximum of two children, known as the left child and the right child. In a pre-order traversal, each node is visited prior to its children. The sequence is as follows: visit the root, traverse the left subtree, and then traverse the right subtree. On the other hand, an in-order traversal visits nodes in this order: left child, root, then right child. Essentially, the task is to rearrange the elements of the array so that the tree can be interpreted as being traversed in the in-order manner. Here are some important steps to address this question: We need to comprehend the connection between the nodes in the pre-order and in-order arrays. We can use the index of the root node (the first node in the pre-order list) to split the tree into the left and right subtrees within the in-order list. Recursively apply the conversion method to each subtree.

Suggested Answer

Starting with a pre-order array [1, 2, 4, 5, 3, 6, 7], we can transform it into an in-order array [4, 2, 5, 1, 6, 3, 7]. Here's how to achieve this: Identify the first element of the pre-order array as the root, which is node '1'. Locate '1' in the in-order array; this divides the array into two sections: [4, 2, 5] for the left subtree and [6, 3, 7] for the right subtree. You now have the left subtree as [4, 2, 5] and the right subtree as [6, 3, 7]. By applying this process recursively to the subtrees, you can construct the binary tree structure. Finally, traversing this tree in in-order will yield the converted array.

Alternative Answer

Starting with the pre-order array [7, 2, 1, 5, 4, 6, 3], we can transform it into the in-order array [1, 2, 4, 5, 6, 7, 3]. The process for handling the array is similar to the previous example. Initially, we designate '7' as the root. The in-order traversal array is split into [1, 2, 4, 5, 6] and [3]. This indicates that the left subtree consists of the nodes [1, 2, 4, 5, 6] while the right subtree contains the node [3]. Continue to divide and conquer until each node is isolated. Doing so will reveal the structure of the binary tree. By performing an in-order traversal of this tree, you can derive the corresponding array.

Question Details

Difficulty & Category

Medium
data structures

Companies

Google

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.