Javatpoint Logo
Javatpoint Logo

Construct Full Binary Tree using its Preorder Traversal and Preorder Traversal of its Mirror Tree

We have to create a software that represents these two Pre-order traversals to develop the binary tree given two arrays that produces Pre-order traversals of a full binary tree and its mirror tree.

A full binary tree is a binary tree which tree has one or more children at each node.

It should be noted that these two traversals cannot be used to build a general binary tree. However, we may construct a complete binary tree with the above traversals even without difficulty.

Example:

Construct Full Binary Tree using its Preorder Traversal and Preorder Traversal of its Mirror Tree

Method 1: Take the two provided arrays, preOrder[] = 1, 2, 5, 6, 4, 7, 8 and preOrderMirror[] = 1,4,8,7,2,6,5

The root of the tree is the leftmost element in both preOrder[] and preOrderMirror[]. The array size is bigger than one and the tree is full. The root's left child must be the value next to 1 in preOrder, and the root's right child must be the value next to 1 in preOrderMirror.

Here In this case, 1 is representing the root, 2 is representing the left child, and 4 is representing the right child.

How can I discover all the nodes in the left subtree?

We know that 2 is the root of all nodes in the left subtree and 4 is the root of all nodes in the right subtree. PreOrderMirror needs all the nodes from 2 be in the left subtree of root node 1, and all nodes from 4 and before 2 be in the right subtree of root node 1. Now that we know that the root is 1, the left subtree's elements are 2, 6, 5, and the right subtree's elements are 4, 8, 7.

We'll use the aforementioned strategy recursively to generate the following tree:

The aforesaid technique is implemented as follows:

C++ Program:

Output:

5 2 6 1 7 4 8

Here, we can see that the Time Complexity will be O(n2)

And, also the Auxiliary Space will be O(n).

Method 2: If we try to look closer, we can notice that the Post-order traversal of the original tree is the inverse of the Pre-order traversal of the mirror tree. Similarly to above, we can also build the tree from supplied Pre-order and Post-order traversals.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA