Check whether the two Binary Search Trees are Identical or Not - GeeksforGeeks

28 Feb, 2022
Given the root nodes of the two binary search trees. The task is to print 1 if the two Binary Search Trees are identical else print 0. Two trees are identical if they are identical structurally and nodes have the same values. 
In the above images, both Tree1 and Tree2 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:  
If both trees are empty then return 1.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.Else return 0 (one is empty and other is not).
If both trees are empty then return 1.
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.
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.
Else return 0 (one is empty and other is not).
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ program to check if two BSTs// are identical #include <iostream>using namespace std; // BST nodestruct Node {    int data;    struct Node* left;    struct Node* right;}; // Utility function to create a new Nodestruct 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 traversalvoid inorder(Node* root){    if (root == NULL)        return;     inorder(root->left);     cout << root->data << " ";     inorder(root->right);} // Function to check if two BSTs// are identicalint 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)            && isIdentical(root1->right, root2->right))            return 1;        else            return 0;    }} // Driver codeint 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;}
// Java program to check if two BSTs// are identicalclass GFG{ // BST nodestatic class Node{    int data;    Node left;    Node right;}; // Utility function to create a new Nodestatic Node newNode(int data){    Node node = new Node();    node.data = data;    node.left = null;    node.right = null;     return node;} // Function to perform inorder traversalstatic 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 identicalstatic 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 codepublic 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 program to construct all unique# BSTs for keys from 1 to n # Binary Tree Node""" A utility function to create anew 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 traversaldef inorder(root) :     if (root == None):        return     inorder(root.left)     print(root.data, end = " ")     inorder(root.right) # Function to check if two BSTs# are identicaldef 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 Codeif __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# program to check if two BSTs// are identicalusing System; class GFG{ // BST nodeclass Node{    public int data;    public Node left;    public Node right;}; // Utility function to create a new Nodestatic Node newNode(int data){    Node node = new Node();    node.data = data;    node.left = null;    node.right = null;     return node;} // Function to perform inorder traversalstatic 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 identicalstatic 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 codepublic 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
<script>// Javascript program to check if two BSTs// are identical // BST nodeclass Node{    // Utility function to create a new Node    constructor(data)    {        this.data = data;        this.left = this.right = null;    }} // Function to perform inorder traversalfunction inorder(root){    if (root == null)        return;      inorder(root.left);      document.write(root.data + " ");      inorder(root.right);} // Function to check if two BSTs// are identicalfunction 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 codelet 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>
Both BSTs are identical
 
Time Complexity: O(N)Auxiliary Space: O(N) 
SHUBHAMSINGH10
29AjayKumar
princiraj1992
pankajsharmagfg
rag2127
surinderdawra388
Binary Search Tree
Data Structures
Recursion
Data Structures
Recursion
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorted Array to Balanced BST
Optimal Binary Search Tree | DP-24
Red-Black Tree | Set 2 (Insert)
Inorder Successor in Binary Search Tree
Find the node with minimum value in a Binary Search Tree
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
DSA Sheet by Love Babbar
Doubly Linked List | Set 1 (Introduction and Insertion)
How to Start Learning DSA?