Open In App

Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree

Last Updated : 18 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two arrays that represent Preorder traversals of a full binary tree and its mirror tree, we need to write a program to construct the binary tree using these two Preorder traversals.
A Full Binary Tree is a binary tree where every node has either 0 or 2 children.

Note: It is not possible to construct a general binary tree using these two traversals. But we can create a full binary tree using the above traversals without any ambiguity. For more details refer to this article.

Examples: 

Input :  preOrder[] = {1,2,4,5,3,6,7}
         preOrderMirror[] = {1,3,7,6,2,5,4}

Output :          1
               /    \
              2      3
            /   \   /  \
           4     5 6    7
  • Method 1: Let us consider the two given arrays as preOrder[] = {1, 2, 4, 5, 3, 6, 7} and preOrderMirror[] = {1 ,3 ,7 ,6 ,2 ,5 ,4}. 
    In both preOrder[] and preOrderMirror[], the leftmost element is root of tree. Since the tree is full and array size is more than 1. The value next to 1 in preOrder[], must be left child of the root and value next to 1 in preOrderMirror[] must be right child of root. So we know 1 is root and 2 is left child and 3 is the right child. How to find the all nodes in left subtree? We know 2 is root of all nodes in left subtree and 3 is root of all nodes in right subtree. All nodes from and 2 in preOrderMirror[] must be in left subtree of root node 1 and all node after 3 and before 2 in preOrderMirror[] must be in right subtree of root node 1. Now we know 1 is root, elements {2, 5, 4} are in left subtree, and the elements {3, 7, 6} are in the right subtree.
           1
        /    \
       /      \
    {2,5,4}  {3,7,6}
  • We will recursively follow the above approach and get the below tree:
                  1
               /    \
              2      3
            /   \   /  \
           4     5 6    7

Below is the implementation of above approach: 

C++




// C++ program to construct full binary tree
// using its preorder traversal and preorder
// traversal of its mirror tree
  
#include<bits/stdc++.h>
using namespace std;
  
// A Binary Tree Node
struct Node
{
    int data;
    struct Node *left, *right;
};
  
// Utility function to create a new tree node
Node* newNode(int data)
{
    Node *temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
  
// A utility function to print inorder traversal 
// of a Binary Tree
void printInorder(Node* node)
{
    if (node == NULL)
        return;
  
    printInorder(node->left);
    printf("%d ", node->data);
    printInorder(node->right);
}
  
// A recursive function to construct Full binary tree
//  from pre[] and preM[]. preIndex is used to keep 
// track of index in pre[]. l is low index and h is high 
//index for the current subarray in preM[]
Node* constructBinaryTreeUtil(int pre[], int preM[],
                    int &preIndex, int l,int h,int size)
{    
    // Base case
    if (preIndex >= size || l > h)
        return NULL;
  
    // The first node in preorder traversal is root. 
    // So take the node at preIndex from preorder and 
    // make it root, and increment preIndex
    Node* root = newNode(pre[preIndex]);
        ++(preIndex);
  
    // If the current subarray has only one element, 
    // no need to recur
    if (l == h)
        return root;
      
    // Search the next element of pre[] in preM[]
    int i;
    for (i = l; i <= h; ++i)
        if (pre[preIndex] == preM[i])
            break;
  
    // construct left and right subtrees recursively    
    if (i <= h)
    {
        root->left = constructBinaryTreeUtil (pre, preM, 
                                    preIndex, i, h, size);
        root->right = constructBinaryTreeUtil (pre, preM, 
                                 preIndex, l+1, i-1, size);
    }
   
     // return root
    return root;    
}
  
// function to construct full binary tree
// using its preorder traversal and preorder
// traversal of its mirror tree
void constructBinaryTree(Node* root,int pre[],
                        int preMirror[], int size)
{
    int preIndex = 0;
    int preMIndex = 0;
  
    root =  constructBinaryTreeUtil(pre,preMirror,
                            preIndex,0,size-1,size);
  
    printInorder(root);
}
  
// Driver program to test above functions
int main()
{
    int preOrder[] = {1,2,4,5,3,6,7};
    int preOrderMirror[] = {1,3,7,6,2,5,4};
  
    int size = sizeof(preOrder)/sizeof(preOrder[0]);
  
    Node* root = new Node; 
  
    constructBinaryTree(root,preOrder,preOrderMirror,size);
  
    return 0;
}


Java




// Java program to construct full binary tree 
// using its preorder traversal and preorder 
// traversal of its mirror tree 
class GFG
{
  
// A Binary Tree Node 
static class Node 
    int data; 
    Node left, right; 
}; 
static class INT
{
    int a;
    INT(int a){this.a=a;}
}
  
// Utility function to create a new tree node 
static Node newNode(int data) 
    Node temp = new Node(); 
    temp.data = data; 
    temp.left = temp.right = null
    return temp; 
  
// A utility function to print inorder traversal 
// of a Binary Tree 
static void printInorder(Node node) 
    if (node == null
        return
  
    printInorder(node.left); 
    System.out.printf("%d ", node.data); 
    printInorder(node.right); 
  
// A recursive function to construct Full binary tree 
// from pre[] and preM[]. preIndex is used to keep 
// track of index in pre[]. l is low index and h is high 
//index for the current subarray in preM[] 
static Node conBinaryTreeUtil(int pre[], int preM[], 
                    INT preIndex, int l, int h, int size) 
    // Base case 
    if (preIndex.a >= size || l > h) 
        return null
  
    // The first node in preorder traversal is root. 
    // So take the node at preIndex from preorder and 
    // make it root, and increment preIndex 
    Node root = newNode(pre[preIndex.a]); 
        ++(preIndex.a); 
  
    // If the current subarray has only one element, 
    // no need to recur 
    if (l == h) 
        return root; 
      
    // Search the next element of pre[] in preM[] 
    int i; 
    for (i = l; i <= h; ++i) 
        if (pre[preIndex.a] == preM[i]) 
            break
  
    // construct left and right subtrees recursively 
    if (i <= h) 
    
        root.left = conBinaryTreeUtil (pre, preM, 
                                    preIndex, i, h, size); 
        root.right = conBinaryTreeUtil (pre, preM, 
                                preIndex, l + 1, i - 1, size); 
    
  
    // return root 
    return root;     
  
// function to construct full binary tree 
// using its preorder traversal and preorder 
// traversal of its mirror tree 
static void conBinaryTree(Node root,int pre[], 
                        int preMirror[], int size) 
    INT preIndex = new INT(0); 
    int preMIndex = 0
  
    root = conBinaryTreeUtil(pre,preMirror, 
                            preIndex, 0, size - 1, size); 
  
    printInorder(root); 
  
// Driver code
public static void main(String args[])
    int preOrder[] = {1,2,4,5,3,6,7}; 
    int preOrderMirror[] = {1,3,7,6,2,5,4}; 
  
    int size = preOrder.length; 
  
    Node root = new Node(); 
  
    conBinaryTree(root,preOrder,preOrderMirror,size); 
  
// This code is contributed by Arnab Kundu


Python3




# Python3 program to construct full binary 
# tree using its preorder traversal and 
# preorder traversal of its mirror tree 
  
# Utility function to create a new tree node 
class newNode:
    def __init__(self,data):
        self.data = data
        self.left = self.right = None
  
# A utility function to print inorder
# traversal of a Binary Tree 
def printInorder(node): 
    if (node == None) :
        return
    printInorder(node.left) 
    print(node.data, end = " "
    printInorder(node.right) 
  
# A recursive function to construct Full  
# binary tree from pre[] and preM[]. 
# preIndex is used to keep track of index 
# in pre[]. l is low index and h is high 
# index for the current subarray in preM[] 
def constructBinaryTreeUtil(pre, preM, preIndex,
                                    l, h, size): 
    # Base case 
    if (preIndex >= size or l > h) :
        return None , preIndex
  
    # The first node in preorder traversal  
    # is root. So take the node at preIndex 
    # from preorder and make it root, and 
    # increment preIndex 
    root = newNode(pre[preIndex]) 
    preIndex += 1
  
    # If the current subarray has only 
    # one element, no need to recur 
    if (l == h): 
        return root, preIndex
  
    # Search the next element of 
    # pre[] in preM[]
    i = 0
    for i in range(l, h + 1): 
        if (pre[preIndex] == preM[i]): 
                break
  
    # construct left and right subtrees
    # recursively 
    if (i <= h): 
  
        root.left, preIndex = constructBinaryTreeUtil(pre, preM, preIndex,
                                                               i, h, size) 
        root.right, preIndex = constructBinaryTreeUtil(pre, preM, preIndex, 
                                                       l + 1, i - 1, size) 
  
    # return root 
    return root, preIndex
  
# function to construct full binary tree 
# using its preorder traversal and preorder 
# traversal of its mirror tree
def constructBinaryTree(root, pre, preMirror, size): 
  
    preIndex = 0
    preMIndex = 0
  
    root, x = constructBinaryTreeUtil(pre, preMirror, preIndex, 
                                             0, size - 1, size) 
  
    Print Inorder(root) 
  
# Driver code 
if __name__ =="__main__":
  
    preOrder = [1, 2, 4, 5, 3, 6, 7]
    preOrderMirror = [1, 3, 7, 6, 2, 5, 4]
  
    size = 7
    root = newNode(0
  
    constructBinaryTree(root, preOrder, 
                        preOrderMirror, size) 
  
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)


C#




// C# program to construct full binary tree 
// using its preorder traversal and preorder 
// traversal of its mirror tree 
using System;
      
class GFG
{
  
// A Binary Tree Node 
public class Node 
    public int data; 
    public Node left, right; 
}; 
public class INT
{
    public int a;
    public INT(int a){this.a=a;}
}
  
// Utility function to create a new tree node 
static Node newNode(int data) 
    Node temp = new Node(); 
    temp.data = data; 
    temp.left = temp.right = null
    return temp; 
  
// A utility function to print inorder traversal 
// of a Binary Tree 
static void printInorder(Node node) 
    if (node == null
        return
  
    printInorder(node.left); 
    Console.Write("{0} ", node.data); 
    printInorder(node.right); 
  
// A recursive function to construct Full binary tree 
// from pre[] and preM[]. preIndex is used to keep 
// track of index in pre[]. l is low index and h is high 
//index for the current subarray in preM[] 
static Node conBinaryTreeUtil(int []pre, int []preM, 
                    INT preIndex, int l, int h, int size) 
    // Base case 
    if (preIndex.a >= size || l > h) 
        return null
  
    // The first node in preorder traversal is root. 
    // So take the node at preIndex from preorder and 
    // make it root, and increment preIndex 
    Node root = newNode(pre[preIndex.a]); 
        ++(preIndex.a); 
  
    // If the current subarray has only one element, 
    // no need to recur 
    if (l == h) 
        return root; 
      
    // Search the next element of pre[] in preM[] 
    int i; 
    for (i = l; i <= h; ++i) 
        if (pre[preIndex.a] == preM[i]) 
            break
  
    // construct left and right subtrees recursively 
    if (i <= h) 
    
        root.left = conBinaryTreeUtil (pre, preM, 
                                    preIndex, i, h, size); 
        root.right = conBinaryTreeUtil (pre, preM, 
                                preIndex, l + 1, i - 1, size); 
    
  
    // return root 
    return root;     
  
// function to construct full binary tree 
// using its preorder traversal and preorder 
// traversal of its mirror tree 
static void conBinaryTree(Node root,int []pre, 
                        int []preMirror, int size) 
    INT preIndex = new INT(0); 
    int preMIndex = 0; 
  
    root = conBinaryTreeUtil(pre,preMirror, 
                            preIndex, 0, size - 1, size); 
  
    printInorder(root); 
  
// Driver code
public static void Main(String []args)
    int []preOrder = {1,2,4,5,3,6,7}; 
    int []preOrderMirror = {1,3,7,6,2,5,4}; 
  
    int size = preOrder.Length; 
  
    Node root = new Node(); 
  
    conBinaryTree(root,preOrder,preOrderMirror,size); 
}
  
/* This code is contributed by PrinciRaj1992 */


Javascript




<script>
    
// JavaScript program to construct full binary tree 
// using its preorder traversal and preorder 
// traversal of its mirror tree 
  
// A Binary Tree Node 
class Node 
    constructor()
    {
        this.data = 0;
        this.left = null;
        this.right = null;
    }
}; 
  
class INT
{
    constructor(a)
    {
        this.a = a;
    }
}
  
// Utility function to create a new tree node 
function newNode(data) 
    var temp = new Node(); 
    temp.data = data; 
    temp.left = temp.right = null
    return temp; 
  
// A utility function to print inorder traversal 
// of a Binary Tree 
function printInorder(node) 
    if (node == null
        return
  
    printInorder(node.left); 
    document.write(node.data + " "); 
    printInorder(node.right); 
  
// A recursive function to construct Full binary tree 
// from pre[] and preM[]. preIndex is used to keep 
// track of index in pre[]. l is low index and h is high 
//index for the current subarray in preM[] 
function conBinaryTreeUtil(pre, preM, preIndex, l, h, size) 
    // Base case 
    if (preIndex.a >= size || l > h) 
        return null
  
    // The first node in preorder traversal is root. 
    // So take the node at preIndex from preorder and 
    // make it root, and increment preIndex 
    var root = newNode(pre[preIndex.a]); 
        ++(preIndex.a); 
  
    // If the current subarray has only one element, 
    // no need to recur 
    if (l == h) 
        return root; 
      
    // Search the next element of pre[] in preM[] 
    var i; 
    for (i = l; i <= h; ++i) 
        if (pre[preIndex.a] == preM[i]) 
            break
  
    // construct left and right subtrees recursively 
    if (i <= h) 
    
        root.left = conBinaryTreeUtil (pre, preM, 
                                    preIndex, i, h, size); 
        root.right = conBinaryTreeUtil (pre, preM, 
                                preIndex, l + 1, i - 1, size); 
    
  
    // return root 
    return root;     
  
// function to construct full binary tree 
// using its preorder traversal and preorder 
// traversal of its mirror tree 
function conBinaryTree(root,pre, preMirror, size) 
    var preIndex = new INT(0); 
    var preMIndex = 0; 
  
    root = conBinaryTreeUtil(pre,preMirror, 
                            preIndex, 0, size - 1, size); 
  
    printInorder(root); 
  
// Driver code
var preOrder = [1,2,4,5,3,6,7]; 
var preOrderMirror = [1,3,7,6,2,5,4]; 
var size = preOrder.length; 
var root = new Node(); 
conBinaryTree(root,preOrder,preOrderMirror,size); 
  
  
</script>


Output

4 2 5 1 6 3 7 

Time Complexity: O(n^2)
Auxiliary Space: O(n), The extra space is used due to the recursion call stack

  • Method 2: If we observe carefully, then the reverse of the Preorder traversal of the mirror tree will be the Postorder traversal of the original tree. We can construct the tree from given Preorder and Postorder traversals in a similar manner as above. You can refer to this article on how to Construct a Full Binary Tree from given preorder and postorder traversals.

 



Previous Article
Next Article

Similar Reads

Construct the full k-ary tree from its preorder traversal
Given an array that contains the preorder traversal of the full k-ary tree, construct the full k-ary tree and print its postorder traversal. A full k-ary tree is a tree where each node has either 0 or k children. Examples: Input : preorder[] = {1, 2, 5, 6, 7, 3, 8, 9, 10, 4} k = 3 Output : Postorder traversal of constructed full k-ary tree is: 5 6
10 min read
Construct a Perfect Binary Tree from Preorder Traversal
Given an array pre[], representing the Preorder traversal of a Perfect Binary Tree consisting of N nodes, the task is to construct a Perfect Binary Tree from the given Preorder Traversal and return the root of the tree. Examples: Input: pre[] = {1, 2, 4, 5, 3, 6, 7}Output: 1 / \ / \ 2 3 / \ / \ / \ / \ 4 5 6 7 Input: pre[] = {1, 2, 3}Output: 1 / \
11 min read
Construct Full Binary Tree from given preorder and postorder traversals
Given two arrays that represent preorder and postorder traversals of a full binary tree, construct the binary tree. Full Binary Tree is a binary tree where every node has either 0 or 2 children. Illustration: Following are examples of Full Trees. 1 / \ 2 3 / \ / \ 4 5 6 7 1 / \ 2 3 / \ 4 5 / \ 6 7 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 It is not possibl
14 min read
Convert a Binary Tree into its Mirror Tree (Invert Binary Tree)
Given a binary tree, the task is to convert the binary tree into its Mirror tree. Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged. Recommended PracticeMirror TreeTry It!The idea is to traverse recursively and swap the right and left subtrees after traversing the subtrees. Follow
15+ min read
Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
Given two binary trees S and T, the task is the check that if S is a subtree of the Tree T. For Example: Input: Tree T - 1 / \ 2 3 / \ / \ 4 5 6 7 Tree S - 2 / \ 4 5 Output: YES Explanation: The above tree is the subtree of the tree T, Hence the output is YES Approach: The idea is to traverse both the tree in Pre-order Traversal and check for each
11 min read
Construct a special tree from given preorder traversal
Given an array 'pre[]' that represents Preorder traversal of a special binary tree where every node has either 0 or 2 children. One more array 'preLN[]' is given which has only two possible values 'L' and 'N'. The value 'L' in 'preLN[]' indicates that the corresponding node in Binary Tree is a leaf node and value 'N' indicates that the correspondin
15+ min read
Construct BST from given preorder traversal using Stack
Given preorder traversal of a binary search tree, construct the BST.For example, if the given traversal is {10, 5, 1, 7, 40, 50}, then the output should be root of following tree. 10 / \ 5 40 / \ \ 1 7 50 We have discussed O(n^2) and O(n) recursive solutions in the previous post. Following is a stack based iterative solution that works in O(n) time
13 min read
Construct BST from given preorder traversal using Sorting
Given preorder traversal of a binary search tree, construct the BST.For example, if the given traversal is {10, 5, 1, 7, 40, 50}, then the output should be root of following tree. 10 / \ 5 40 / \ \ 1 7 50 We have discussed methods to construct binary search tree in previous posts.Here is another method to construct binary search tree when given pre
10 min read
Check if a number is prime in Flipped Upside Down, Mirror Flipped and Mirror Flipped Upside Down
Given an integer N, the task is to check if N is a prime number in Flipped Down, Mirror Flipped and Mirror Flipped Down forms of the given number.Examples: Input: N = 120121 Output: YesExplanation: Flipped forms of the number:Flipped Upside Down - 151051Mirror Flipped - 121021Mirror Upside Down - 150151Since 1510151 and 121021 are both prime number
6 min read
Construct BST from given preorder traversal | Set 1
Given the preorder traversal of a binary search tree, construct the BST. Examples: Input: {10, 5, 1, 7, 40, 50}Output: 10 / \ 5 40 / \ \ 1 7 50 Recommended: Please try your approach on {IDE} first, before moving on to the solution.Naive approach: To solve the problem follow the below idea: The first element of preorder traversal is always the root.
15+ min read
Article Tags :
Practice Tags :