Logo
All Questions

Convert a binary tree from pre-order array to in-order array.

Difficultydata structuresAsked at Google

Question Explain

This question is asking you to convert the pre-order traversal of a binary tree into an in-order traversal. Binary trees are a type of data structure where each node has at most two children, referred to as the left child and the right child.

In a pre-order traversal of a binary tree, each node is visited before its children. The process is performed as follows: visit the root, traverse the left subtree, and then traverse the right subtree.

In contrast, an in-order traversal visits the nodes in the following order: left child, root, then right child. Essentially, it's asking you to rearrange the array elements in such a way that the tree can be interpreted as being traversed in the in-order way.

Here are some key steps to solve this question:

  1. We need to understand the relationship between nodes in the pre-order and in-order array.
  2. We can use the index of the root node (the first node in the pre-order list) in the in-order list to divide the tree into left subtree and right subtree.
  3. Recursively apply the conversion rule to each subtree.

Answer Example 1

Given a pre-order array [1, 2, 4, 5, 3, 6, 7], we can convert it to an in-order array [4, 2, 5, 1, 6, 3, 7].

Here is how you can do it:

Set the first element of pre-order as root, which is node '1'. Find '1' in the in-order array, it separates the array into two parts: [4, 2, 5] and [6, 3, 7]. Now you know the left subtree of root is [4, 2, 5] and the right subtree is [6, 3, 7]. Recursively apply this to the subtrees and you can build the binary tree structure. Then you traverse this tree in in-order you get the converted array.

Answer Example 2

Given a pre-order array [7, 2, 1, 5, 4, 6, 3], we can convert it to an in-order array [1, 2, 4, 5, 6, 7, 3].

We process the array similarly to the previous example.

First, set '7' as the root. The in-order traversal array is divided into [1, 2, 4, 5, 6] and [3]. You get to know the left subtree contains nodes [1, 2, 4, 5, 6] and the right subtree contains node [3]. Keep divide and conquer until you reach the individual nodes. Then, you'll get the binary tree structure. By traversing this tree in in-order, you can obtain the consequent array.

More Questions

Question Quick Reference by Category: