Construct a binary tree from its in-order and pre-order traversals

  • Share this:
Construct a binary tree from its in-order and pre-order traversals

A simple recursive approach to construct a binary tree from its traversals

This is a simple guide on how to construct a binary tree from its in-order and pre-order traversals.

As a remainder,

In-Order : Left -> Root -> Right

Pre-Order : Root -> Left -> Right

Consider the following in-order and pre-order traversals of a binary tree

In-Order : 4, 2, 5, 1, 6, 3, 7

Pre-Order : 1, 2, 4, 5, 3, 6, 7


The root is simply the first element of the pre-order traversal

\"img1\"

Find the root in the in-order traversal and split the traversal into 2 halves of size 3 each. ie., In-order traversal of left and right sub-trees.

Since we just found that the size of in-order traversal of left sub-tree is 3, we can split the pre-order traversal accordingly in to left and right.

So the 3 elements immediately following the root in the pre-order form the pre-order of the left sub-tree and the rest are the pre-order of the right sub-tree.

\"img2\"

Now, consider the left in-order and pre-order traversals and repeat the same process of finding the root.

\"img3\"

Again split it into left and right in-order and pre-order traversals

\"img4\"

Now, there is only 1 element in in-order and pre-order each. So just add them as leaf nodes.

\"img5\"

Repeat for the element 5

\"img6\"

Now the left sub-tree of root element 1 is complete. Repeat the same process for the right sub-tree.

The completed tree would look something like this

\"img7\"


Try writing code for this Leetcode Problem using the methods we just learned

profile.png

Ben Meehan

About author
Software Engineer at Ather Energy. Enjoy Competitive Programming and Blogging. Worked as an technical author intern at OpenGenus.org
Ben Meehan - OpenGenus
0 Comments
Leave a Comment