Skip to content
Related Articles

Related Articles

Print the elements of given two Binary Trees in sorted order

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 24 May, 2022

Given two binary trees, the task is to print the elements of both the binary trees in non-decreasing order.

Examples:

Input: Trees in the image below

Output: 1 2 3 4 5 6
Explanation: The nodes in the 1st and 2nd binary tree are {3, 1, 5} and {4, 2, 6} respectively. Upon merging and sorting the two arrays, the required array becomes {1, 2, 3, 4, 5, 6} which is the required answer.

Input: Trees in the image below

Output: 0 1 2 3 5 8 10

 

Approach: The given problem can be solved using the following steps:

  • Create a map to store each element present in both trees along with there frequencies.
  • Traverse the first tree and insert each element with its frequency in the map.
  • Similarly, traverse the first tree and insert each element with its frequency in the map.
  • Traverse the map and print all elements, their frequency times.

Below is the implementation of the above approach:

C++




// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Structure of a binary tree node
class node {
public:
    int data;
    node* left;
    node* right;
};
 
// Helper function that allocates
// a new node with the given data
node* newNode(int data)
{
    node* Node = new node();
    Node->data = data;
    Node->left = NULL;
    Node->right = NULL;
 
    return (Node);
}
 
// Map to store all elements
// from given two trees
map<int, int> m;
 
// Recursive function to perform
// inorder traversal on tree
void traverse(node* root)
{
    // Base Case
    if (root == NULL)
        return;
    else {
        // Update map
        m[root->data]++;
    }
 
    // Recursive call for left subtree
    traverse(root->left);
 
    // Recursive call for right subtree
    traverse(root->right);
}
 
// Function to print all the elements of
// two given binary trees in sorted order
void printAllElements(node* root1, node* root2)
{
    // Traverse the 1st tree
    traverse(root1);
 
    // Traverse the 2nd tree
    traverse(root2);
 
    // Traverse the map
    for (auto it : m) {
        // Print current element
        // its frequency times
        for (int i = 0; i < it.second; i++) {
            cout << it.first << " ";
        }
    }
}
 
// Driver code
int main()
{
    node* root1 = newNode(8);
    root1->left = newNode(2);
    root1->right = newNode(10);
    root1->left->left = newNode(1);
 
    node* root2 = newNode(5);
    root2->left = newNode(3);
    root2->right = newNode(0);
 
    printAllElements(root1, root2);
 
    return 0;
}

Java




// Java program of the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
// Structure of a binary tree node
public class GFG{
public static class Node {
    int data;
    Node left, right;
    Node(int data)
    {
        left=right=null;
        this.data=data;
    }
}
// Map to store all elements
// from given two trees
public static Map<Integer, Integer> m = new HashMap<>();
 
// Recursive function to perform
// inorder traversal on tree
public static void traverse(Node root)
{
    // Base Case
    if (root == null)
        return;
    else {
        // Update map
        if(m.containsKey(root.data))
        m.put(root.data,m.get(root.data)+1);
        else
        m.put(root.data,1);
    }
 
    // Recursive call for left subtree
    traverse(root.left);
 
    // Recursive call for right subtree
    traverse(root.right);
}
 
// Function to print all the elements of
// two given binary trees in sorted order
public static void printAllElements(Node root1, Node root2)
{
    // Traverse the 1st tree
    traverse(root1);
 
    // Traverse the 2nd tree
    traverse(root2);
 
    // Traverse the map
    for (Map.Entry<Integer,Integer> it : m.entrySet()) {
        // Print current element
        // its frequency times
        for (int i = 0; i < it.getValue(); i++) {
             System.out.print(it.getKey()+" ");
        }
    }
}
 
// Driver code
public static void main(String[] args)
{
    Node root1 = new Node(8);
    root1.left = new Node(2);
    root1.right = new Node(10);
    root1.left.left = new Node(1);
     
    Node root2 = new Node(5);
    root2.left = new Node(3);
    root2.right = new Node(0);
 
    printAllElements(root1, root2);
 
}
}
 
// This code is contributed by Pushpesh raj.

Python3




# Python code for the above approach
 
# Structure of a binary tree node
class node:
    def __init__(self, d):
        self.data = d
        self.left = None
        self.right = None
 
# Map to store all elements
# from given two trees
m = {}
 
# Recursive function to perform
# inorder traversal on tree
def traverse(root):
 
    # Base Case
    if (root == None):
        return
    else:
 
        # Update map
        if (root.data in m):
            m[root.data] += 1
        else:
            m[root.data] = 1
 
    # Recursive call for left subtree
    traverse(root.left)
 
    # Recursive call for right subtree
    traverse(root.right)
 
# Function to print all the elements of
# two given binary trees in sorted order
def printAllElements(root1, root2):
 
    # Traverse the 1st tree
    traverse(root1)
 
    # Traverse the 2nd tree
    traverse(root2)
    v = []
 
    # Traverse the map
    for key in m:
 
        # Print current element
        # its frequency times
        for i in range(m[key]):
            v.append(key)
 
    v.sort()
    for i in range(len(v)):
        print(v[i], end=" ")
 
# Driver code
root1 = node(8)
root1.left = node(2)
root1.right = node(10)
root1.left.left = node(1)
 
root2 = node(5)
root2.left = node(3)
root2.right = node(0)
 
printAllElements(root1, root2)
 
# This code is contributed by Saurabh Jaiswal

Javascript




<script>
       // JavaScript code for the above approach
 
       // Structure of a binary tree node
       class node {
           constructor(d) {
               this.data = d;
               this.left = null;
               this.right = null;
           }
       };
 
       // Map to store all elements
       // from given two trees
       let m = new Map();
 
       // Recursive function to perform
       // inorder traversal on tree
       function traverse(root)
       {
        
           // Base Case
           if (root == null)
               return;
           else
           {
            
               // Update map
               if (m.has(root.data))
               {
                   m.set(root.data, m.get(root.data) + 1);
               }
               else {
                   m.set(root.data, 1)
               }
           }
 
           // Recursive call for left subtree
           traverse(root.left);
 
           // Recursive call for right subtree
           traverse(root.right);
       }
 
       // Function to print all the elements of
       // two given binary trees in sorted order
       function printAllElements(root1, root2)
       {
        
           // Traverse the 1st tree
           traverse(root1);
 
           // Traverse the 2nd tree
           traverse(root2);
           let v = []
            
           // Traverse the map
           for (let [key, val] of m)
           {
            
               // Print current element
               // its frequency times
               for (let i = 0; i < val; i++) {
                   v.push(key);
               }
           }
           v.sort(function (a, b) { return a - b })
           for (let i = 0; i < v.length; i++) {
               document.write(v[i] + " ")
           }
       }
 
       // Driver code
       let root1 = new node(8);
       root1.left = new node(2);
       root1.right = new node(10);
       root1.left.left = new node(1);
 
       let root2 = new node(5);
       root2.left = new node(3);
       root2.right = new node(0);
 
       printAllElements(root1, root2);
 
      // This code is contributed by Potta Lokesh
   </script>

 
 

Output

0 1 2 3 5 8 10 

 

Time Complexity: O(N*log N)
Auxiliary Space: O(N)

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!