Open In App

Check whether the two Binary Search Trees are Identical or Not

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Given the root nodes of the two binary search trees. The task is to print “Both BSTs are identical” if the two Binary Search Trees are identical else print “Both BSTs are identical”. Two trees are identical if they are identical structurally and nodes have the same values.

Tree1:                                         
         5                                               
        / \
      3   8
     / \   
    2   4

Tree2:
       5
      / \
     3   8
    / \   
   2   4

Here in both the trees the structure is same and the nodes having same value so we can say that Both BSTs are identical.

To identify if two trees are identical, we need to traverse both trees simultaneously, and while traversing we need to compare data and children of the trees.

Below is the step by step algorithm to check if two BSTs are identical: 

  1. If both trees are empty then return 1.
  2. Else If both trees are non -empty 
    • Check data of the root nodes (tree1->data == tree2->data)
    • Check left subtrees recursively i.e., call sameTree(tree1->left_subtree, tree2->left_subtree)
    • Check right subtrees recursively i.e., call sameTree(tree1->right_subtree, tree2->right_subtree)
    • If the values returned in the above three steps are true then return 1.
  3. Else return 0 (one is empty and other is not).

Below is the implementation of the above approach: 

C++




// C++ program to check if two BSTs
// are identical
 
#include <iostream>
using namespace std;
 
// BST node
struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};
 
// Utility function to create a new Node
struct Node* newNode(int data)
{
    struct Node* node = (struct Node*)
        malloc(sizeof(struct Node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
 
    return node;
}
 
// Function to perform inorder traversal
void inorder(Node* root)
{
    if (root == NULL)
        return;
 
    inorder(root->left);
 
    cout << root->data << " ";
 
    inorder(root->right);
}
 
// Function to check if two BSTs
// are identical
int isIdentical(Node* root1, Node* root2)
{
    // Check if both the trees are empty
    if (root1 == NULL && root2 == NULL)
        return 1;
    // If any one of the tree is non-empty
    // and other is empty, return false
    else if (root1 == NULL || root2 == NULL)
        return 0;
    else { // Check if current data of both trees equal
        // and recursively check for left and right subtrees
        if (root1->data == root2->data && isIdentical(root1->left, root2->left)
            && isIdentical(root1->right, root2->right))
            return 1;
        else
            return 0;
    }
}
 
// Driver code
int main()
{
    struct Node* root1 = newNode(5);
    struct Node* root2 = newNode(5);
    root1->left = newNode(3);
    root1->right = newNode(8);
    root1->left->left = newNode(2);
    root1->left->right = newNode(4);
 
    root2->left = newNode(3);
    root2->right = newNode(8);
    root2->left->left = newNode(2);
    root2->left->right = newNode(4);
 
    if (isIdentical(root1, root2))
        cout << "Both BSTs are identical";
    else
        cout << "BSTs are not identical";
 
    return 0;
}


C




// C program to check if two BSTs
// are identical
 
#include <stdio.h>
#include <stdlib.h>
 
 
// BST node
struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};
 
// Utility function to create a new Node
struct Node* newNode(int data)
{
    struct Node* node = (struct Node*)malloc(sizeof(struct Node));
        
    node->data = data;
    node->left = NULL;
    node->right = NULL;
 
    return node;
}
 
// Function to perform inorder traversal
void inorder(struct Node* root)
{
    if (root == NULL)
        return;
 
    inorder(root->left);
 
    printf("%d " ,root->data);
 
    inorder(root->right);
}
 
// Function to check if two BSTs
// are identical
int isIdentical(struct Node* root1,struct Node* root2)
{
    // Check if both the trees are empty
    if (root1 == NULL && root2 == NULL)
        return 1;
    // If any one of the tree is non-empty
    // and other is empty, return false
    else if (root1 == NULL || root2 == NULL)
        return 0;
    else { // Check if current data of both trees equal
        // and recursively check for left and right subtrees
        if (root1->data == root2->data && isIdentical(root1->left, root2->left)
            && isIdentical(root1->right, root2->right))
            return 1;
        else
            return 0;
    }
}
 
// Driver code
int main()
{
    struct Node* root1 = newNode(5);
    struct Node* root2 = newNode(5);
    root1->left = newNode(3);
    root1->right = newNode(8);
    root1->left->left = newNode(2);
    root1->left->right = newNode(4);
 
    root2->left = newNode(3);
    root2->right = newNode(8);
    root2->left->left = newNode(2);
    root2->left->right = newNode(4);
 
    if (isIdentical(root1, root2))
        printf( "Both BSTs are identical");
    else
        printf("BSTs are not identical") ;
 
    return 0;
}
 
// This code is contributed by sanskar84.


Java




// Java program to check if two BSTs
// are identical
class GFG
{
 
// BST node
static class Node
{
    int data;
    Node left;
    Node right;
};
 
// Utility function to create a new Node
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = null;
    node.right = null;
 
    return node;
}
 
// Function to perform inorder traversal
static void inorder(Node root)
{
    if (root == null)
        return;
 
    inorder(root.left);
 
    System.out.print(root.data + " ");
 
    inorder(root.right);
}
 
// Function to check if two BSTs
// are identical
static int isIdentical(Node root1,
                       Node root2)
{
    // Check if both the trees are empty
    if (root1 == null && root2 == null)
        return 1;
         
    // If any one of the tree is non-empty
    // and other is empty, return false
    else if (root1 != null &&
             root2 == null)
        return 0;
    else if (root1 == null &&
             root2 != null)
        return 0;
    else
    {
        // Check if current data of both trees equal
        // and recursively check for left and right subtrees
        if (root1.data == root2.data &&
            isIdentical(root1.left, root2.left) == 1 &&
            isIdentical(root1.right, root2.right) == 1)
            return 1;
        else
            return 0;
    }
}
 
// Driver code
public static void main(String[] args)
{
    Node root1 = newNode(5);
    Node root2 = newNode(5);
    root1.left = newNode(3);
    root1.right = newNode(8);
    root1.left.left = newNode(2);
    root1.left.right = newNode(4);
 
    root2.left = newNode(3);
    root2.right = newNode(8);
    root2.left.left = newNode(2);
    root2.left.right = newNode(4);
 
    if (isIdentical(root1, root2)==1)
        System.out.print("Both BSTs are identical");
    else
        System.out.print("BSTs are not identical");
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 program to construct all unique
# BSTs for keys from 1 to n
 
# Binary Tree Node
""" A utility function to create a
new BST node """
class newNode:
 
    # Construct to create a newNode
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# Function to perform inorder traversal
def inorder(root) :
 
    if (root == None):
        return
 
    inorder(root.left)
 
    print(root.data, end = " ")
 
    inorder(root.right)
 
# Function to check if two BSTs
# are identical
def isIdentical(root1, root2) :
 
    # Check if both the trees are empty
    if (root1 == None and root2 == None) :
        return 1
         
    # If any one of the tree is non-empty
    # and other is empty, return false
    elif (root1 != None and root2 == None) :
        return 0
    elif (root1 == None and root2 != None) :
        return 0
    else: # Check if current data of both trees
          # equal and recursively check for left
          # and right subtrees
        if (root1.data == root2.data and
            isIdentical(root1.left, root2.left)
            and isIdentical(root1.right, root2.right)) :
            return 1
        else:
            return 0
     
# Driver Code
if __name__ == '__main__':
 
    root1 = newNode(5)
    root2 = newNode(5)
    root1.left = newNode(3)
    root1.right = newNode(8)
    root1.left.left = newNode(2)
    root1.left.right = newNode(4)
 
    root2.left = newNode(3)
    root2.right = newNode(8)
    root2.left.left = newNode(2)
    root2.left.right = newNode(4)
 
    if (isIdentical(root1, root2)):
        print("Both BSTs are identical")
    else:
        print("BSTs are not identical")
 
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)


C#




// C# program to check if two BSTs
// are identical
using System;
 
class GFG
{
 
// BST node
class Node
{
    public int data;
    public Node left;
    public Node right;
};
 
// Utility function to create a new Node
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = null;
    node.right = null;
 
    return node;
}
 
// Function to perform inorder traversal
static void inorder(Node root)
{
    if (root == null)
        return;
 
    inorder(root.left);
 
    Console.Write(root.data + " ");
 
    inorder(root.right);
}
 
// Function to check if two BSTs
// are identical
static int isIdentical(Node root1,
                       Node root2)
{
    // Check if both the trees are empty
    if (root1 == null && root2 == null)
        return 1;
         
    // If any one of the tree is non-empty
    // and other is empty, return false
    else if (root1 != null &&
             root2 == null)
        return 0;
    else if (root1 == null &&
             root2 != null)
        return 0;
    else
    {
        // Check if current data of both trees equal
        // and recursively check for left and right subtrees
        if (root1.data == root2.data &&
            isIdentical(root1.left, root2.left) == 1 &&
            isIdentical(root1.right, root2.right) == 1)
            return 1;
        else
            return 0;
    }
}
 
// Driver code
public static void Main(String[] args)
{
    Node root1 = newNode(5);
    Node root2 = newNode(5);
    root1.left = newNode(3);
    root1.right = newNode(8);
    root1.left.left = newNode(2);
    root1.left.right = newNode(4);
 
    root2.left = newNode(3);
    root2.right = newNode(8);
    root2.left.left = newNode(2);
    root2.left.right = newNode(4);
 
    if (isIdentical(root1, root2) == 1)
        Console.Write("Both BSTs are identical");
    else
        Console.Write("BSTs are not identical");
}
}
 
// This code is contributed by PrinciRaj1992


Javascript




<script>
// Javascript program to check if two BSTs
// are identical
 
// BST node
class Node
{
    // Utility function to create a new Node
    constructor(data)
    {
        this.data = data;
        this.left = this.right = null;
    }
}
 
// Function to perform inorder traversal
function inorder(root)
{
    if (root == null)
        return;
  
    inorder(root.left);
  
    document.write(root.data + " ");
  
    inorder(root.right);
}
 
// Function to check if two BSTs
// are identical
function isIdentical(root1,root2)
{
    // Check if both the trees are empty
    if (root1 == null && root2 == null)
        return 1;
          
    // If any one of the tree is non-empty
    // and other is empty, return false
    else if (root1 != null &&
             root2 == null)
        return 0;
    else if (root1 == null &&
             root2 != null)
        return 0;
    else
    {
        // Check if current data of both trees equal
        // and recursively check for left and right subtrees
        if (root1.data == root2.data &&
            isIdentical(root1.left, root2.left) == 1 &&
            isIdentical(root1.right, root2.right) == 1)
            return 1;
        else
            return 0;
    }
}
 
// Driver code
let root1 = new Node(5);
    let root2 = new Node(5);
    root1.left = new Node(3);
    root1.right = new Node(8);
    root1.left.left = new Node(2);
    root1.left.right = new Node(4);
  
    root2.left = new Node(3);
    root2.right = new Node(8);
    root2.left.left = new Node(2);
    root2.left.right = new Node(4);
  
    if (isIdentical(root1, root2)==1)
        document.write("Both BSTs are identical");
    else
        document.write("BSTs are not identical");
 
// This code is contributed by avanitrachhadiya2155
</script>


Output

Both BSTs are identical

Complexity Analysis:

  • Time Complexity: O(N)
  • Auxiliary Space: O(N) 

Another Approach:

To solve the problem follow the below idea:

If two binary search trees are identical, their Preorder, Inorder and Postorder traversals will also be the same.

Below is the implementation of the above approach:

C++




// C++ program to check if two binary search trees are
// identical or not
#include <bits/stdc++.h>
using namespace std;
 
// A binary tree node
class Node {
public:
    int data;
    Node* left;
    Node* right;
 
    Node(int d)
    {
        this->data = d;
        this->left = NULL;
        this->right = NULL;
    }
};
 
// function to check inorder traversal
void inOrder(Node* root, vector<int>& sol)
{
    if (root == NULL)
        return;
    inOrder(root->left, sol);
    sol.push_back(root->data);
    inOrder(root->right, sol);
}
 
// function to check preorder traversal
void preOrder(Node* root, vector<int>& sol)
{
 
    if (root == NULL)
        return;
    sol.push_back(root->data);
    preOrder(root->left, sol);
    preOrder(root->right, sol);
}
 
// function to check postorder traversal
void postOrder(Node* root, vector<int>& sol)
{
 
    if (root == NULL)
        return;
    postOrder(root->left, sol);
    postOrder(root->right, sol);
    sol.push_back(root->data);
}
 
// Function to check if two trees are identical
bool isIdentical(Node* root1, Node* root2)
{
    // Create two vector to store traversals
    vector<int> res1;
    vector<int> res2;
 
    // check inOrder
    inOrder(root1, res1);
    inOrder(root2, res2);
    if (res1 != res2)
        return false;
 
    // clear previous result to reuse vector
    res1.clear();
    res2.clear();
 
    // check PreOrder
    preOrder(root1, res1);
    preOrder(root2, res2);
    if (res1 != res2)
        return false;
 
    // clear previous result to reuse vector
    res1.clear();
    res2.clear();
 
    // check PostOrder
    postOrder(root1, res1);
    postOrder(root2, res2);
    if (res1 != res2)
        return false;
 
    return true;
}
 
// Driver code
int main()
{
    struct Node* root1 = new Node(5);
    struct Node* root2 = new Node(5);
    root1->left = new Node(3);
    root1->right = new Node(8);
    root1->left->left = new Node(2);
    root1->left->right = new Node(4);
 
    root2->left = new Node(3);
    root2->right = new Node(8);
    root2->left->left = new Node(2);
    root2->left->right = new Node(4);
    // Function call
    if (isIdentical(root1, root2)) {
        cout << "Both BSTs are identical." << endl;
    }
    else {
        cout << "BSTs are not identical." << endl;
    }
 
    return 0;
}
 
// This code is contributed by Yash Agarwal(yashagarwal2852002)


Java




// Java program to check if two binary search trees are
// identical or not
import java.util.*;
 
// A binary tree node
class Node {
    int data;
    Node left, right;
 
    Node(int d)
    {
        this.data = d;
        this.left = null;
        this.right = null;
    }
}
 
// Main class
public class Main {
 
    // function to check inorder traversal
    static void inOrder(Node root, ArrayList<Integer> sol)
    {
        if (root == null)
            return;
        inOrder(root.left, sol);
        sol.add(root.data);
        inOrder(root.right, sol);
    }
 
    // function to check preorder traversal
    static void preOrder(Node root, ArrayList<Integer> sol)
    {
        if (root == null)
            return;
        sol.add(root.data);
        preOrder(root.left, sol);
        preOrder(root.right, sol);
    }
 
    // function to check postorder traversal
    static void postOrder(Node root, ArrayList<Integer> sol)
    {
        if (root == null)
            return;
        postOrder(root.left, sol);
        postOrder(root.right, sol);
        sol.add(root.data);
    }
 
    // Function to check if two trees are identical
    static boolean isIdentical(Node root1, Node root2)
    {
        // Create two array lists to store traversals
        ArrayList<Integer> res1 = new ArrayList<Integer>();
        ArrayList<Integer> res2 = new ArrayList<Integer>();
 
        // check inOrder
        inOrder(root1, res1);
        inOrder(root2, res2);
        if (!res1.equals(res2))
            return false;
 
        // clear previous result to reuse array list
        res1.clear();
        res2.clear();
 
        // check PreOrder
        preOrder(root1, res1);
        preOrder(root2, res2);
        if (!res1.equals(res2))
            return false;
 
        // clear previous result to reuse array list
        res1.clear();
        res2.clear();
 
        // check PostOrder
        postOrder(root1, res1);
        postOrder(root2, res2);
        if (!res1.equals(res2))
            return false;
 
        return true;
    }
 
    // Driver code
    public static void main(String args[])
    {
        Node root1 = new Node(5);
        Node root2 = new Node(5);
        root1.left = new Node(3);
        root1.right = new Node(8);
        root1.left.left = new Node(2);
        root1.left.right = new Node(4);
 
        root2.left = new Node(3);
        root2.right = new Node(8);
        root2.left.left = new Node(2);
        root2.left.right = new Node(4);
 
        // Function call
        if (isIdentical(root1, root2)) {
            System.out.println("Both BSTs are identical.");
        }
        else {
            System.out.println("BSTs are not identical.");
        }
    }
}


Python3




# Python3 program to check if two binary search trees are identical or not
 
# A binary tree node
class Node:
    def __init__(self, d):
        self.data = d
        self.left = None
        self.right = None
 
# function to check inorder traversal
def inOrder(root, sol):
    if root is None:
        return
    inOrder(root.left, sol)
    sol.append(root.data)
    inOrder(root.right, sol)
 
# function to check preorder traversal
def preOrder(root, sol):
    if root is None:
        return
    sol.append(root.data)
    preOrder(root.left, sol)
    preOrder(root.right, sol)
 
# function to check postorder traversal
def postOrder(root, sol):
    if root is None:
        return
    postOrder(root.left, sol)
    postOrder(root.right, sol)
    sol.append(root.data)
 
# Function to check if two trees are identical
def isIdentical(root1, root2):
    # Create two list to store traversals
    res1 = []
    res2 = []
 
    # check inOrder
    inOrder(root1, res1)
    inOrder(root2, res2)
    if res1 != res2:
        return False
 
    # clear previous result to reuse list
    res1.clear()
    res2.clear()
 
    # check PreOrder
    preOrder(root1, res1)
    preOrder(root2, res2)
    if res1 != res2:
        return False
 
    # clear previous result to reuse list
    res1.clear()
    res2.clear()
 
    # check PostOrder
    postOrder(root1, res1)
    postOrder(root2, res2)
    if res1 != res2:
        return False
 
    return True
 
# Driver code
if __name__ == "__main__":
    root1 = Node(5)
    root2 = Node(5)
    root1.left = Node(3)
    root1.right = Node(8)
    root1.left.left = Node(2)
    root1.left.right = Node(4)
 
    root2.left = Node(3)
    root2.right = Node(8)
    root2.left.left = Node(2)
    root2.left.right = Node(4)
    # Function call
    if isIdentical(root1, root2):
        print("Both BSTs are identical.")
    else:
        print("BSTs are not identical.")
# This code is contributed by divyansh2212


Javascript




// JavaScript Program to check if two binary search trees are
// identical or not
// a binary tree node
class Node{
    constructor(d){
        this.data = d;
        this.left = null;
        this.right = null;
    }
}
// a function to serialize the arrays into strings and compare them
const equalCheck = (a,b)=>{
    return JSON.stringify(a) === JSON.stringify(b);
}
let res = [];
// function to check inorder traversal
function inOrder(root){
    if(root == null) return res;
    inOrder(root.left);
    res.push(root.data);
    inOrder(root.right);
    return res;
}
 
// function to check preorder traversal
function preOrder(root){
    if(root == null) return res;
    res.push(root.data);
    preOrder(root.left);
    preOrder(root.right);
}
 
// function to check postorder traversal
function postOrder(root){
    if(root == null) return res;
    postOrder(root.left);
    postOrder(root.right);
    res.push(root.data);
}
 
// function to check if two  trees are idnetical
function isIdentical(root1, root2){
    // create two vector to store traversal
    let res1 = [];
    let res2 = [];
     
    // check inorder
    res1 = inOrder(root1);
    res = [];
    res2 = inOrder(root2);
    res = [];
    if(equalCheck(res1, res2) == false) return false;
     
    // check preorder
    res1 = preOrder(root1);
    res = [];
    res2 = preOrder(root2);
    res = [];
    if(equalCheck(res1, res2) == false) return false;
     
    // check postorder
    res1 = postOrder(root1);
    res = [];
    res2 = postOrder(root2);
    if(equalCheck(res1, res2) == false) return false;
     
    return true;
}
 
// driver code
let root1 = new Node(5);
let root2 = new Node(5);
 
root1.left = new Node(3);
root1.right = new Node(8);
root1.left.left = new Node(2);
root1.left.right = new Node(4);
 
root2.left = new Node(3);
root2.right = new Node(8);
root2.left.left = new Node(2);
root2.left.right = new Node(4);
 
// function call
if(isIdentical(root1, root2)){
    console.log("Both BSTs are identical.");
}else{
    console.log("BSTs are not identical.");
}


C#




// C# program for the above approach
 
using System;
using System.Collections.Generic;
 
// Binary tree node
class Node {
    public int data;
    public Node left, right;
 
    public Node(int d)
    {
        this.data = d;
        this.left = null;
        this.right = null;
    }
}
 
public class MainClass {
    // function to check inorder traversal
    static void inOrder(Node root, List<int> sol)
    {
        if (root == null)
            return;
        inOrder(root.left, sol);
        sol.Add(root.data);
        inOrder(root.right, sol);
    }
 
    // function to check preorder traversal
    static void preOrder(Node root, List<int> sol)
    {
        if (root == null)
            return;
        sol.Add(root.data);
        preOrder(root.left, sol);
        preOrder(root.right, sol);
    }
 
    // function to check postorder traversal
    static void postOrder(Node root, List<int> sol)
    {
        if (root == null)
            return;
        postOrder(root.left, sol);
        postOrder(root.right, sol);
        sol.Add(root.data);
    }
 
    // Function to check if two trees are identical
    static bool isIdentical(Node root1, Node root2)
    {
        // Create two lists to store traversals
        List<int> res1 = new List<int>();
        List<int> res2 = new List<int>();
 
        // check inOrder
        inOrder(root1, res1);
        inOrder(root2, res2);
        if (!res1.Equals(res2))
            return false;
 
        // clear previous result to reuse list
        res1.Clear();
        res2.Clear();
 
        // check PreOrder
        preOrder(root1, res1);
        preOrder(root2, res2);
        if (!res1.Equals(res2))
            return false;
 
        // clear previous result to reuse list
        res1.Clear();
        res2.Clear();
 
        // check PostOrder
        postOrder(root1, res1);
        postOrder(root2, res2);
        if (!res1.Equals(res2))
            return false;
 
        return true;
    }
 
    // Driver code
    static void Main()
    {
        Node root1 = new Node(5);
        Node root2 = new Node(5);
        root1.left = new Node(3);
        root1.right = new Node(8);
        root1.left.left = new Node(2);
        root1.left.right = new Node(4);
 
        root2.left = new Node(3);
        root2.right = new Node(8);
        root2.left.left = new Node(2);
        root2.left.right = new Node(4);
 
        // Function call
        if (!isIdentical(root1, root2)) {
            Console.WriteLine("Both BSTs are identical.");
        }
        else {
            Console.WriteLine("BSTs are not identical.");
        }
    }
}
 
// This code is contributed by codebraxnzt


Output

Both BSTs are identical.

Time Complexity: O(NlogN)
Auxiliary Space: O(N) 



Last Updated : 17 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads