Skip to content
Related Articles

Related Articles

Program to Determine if given Two Trees are Identical or not

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 20 Sep, 2022
Improve Article
Save Article

Write a function to determine if two trees are identical or not:

Two trees are identical when they have the same data and the arrangement of data is also the same

Examples:

Input:         1                    1
                 /   \                /   \
               2      3            2      3
             /                    /
           4                   4

Output: Both trees are identical

Input:         1                    1
                 /   \                /   \
               2      3            5      3
                     /             /
                  4             4

Output: Trees are not identical

Approach: To solve the problem follow the below idea:

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

Follow the given steps to solve the problem:

  • If both trees are empty then return 1(Base case)
  • Else If both trees are non-empty
    • Check data of the root nodes (tree1->data ==  tree2->data)
    • Check left subtrees recursively
    • Check right subtrees recursively
    • If the above three statements are true then return 1
  • Else return 0 (one is empty and the other is not)

Below is the implementation of this approach:

C++




// C++ program to see if two trees are identical
#include <bits/stdc++.h>
using namespace std;
 
/* A binary tree node has data, pointer to left child
and a pointer to right child */
class node {
public:
    int data;
    node* left;
    node* right;
};
 
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
node* newNode(int data)
{
    node* Node = new node();
    Node->data = data;
    Node->left = NULL;
    Node->right = NULL;
 
    return (Node);
}
 
/* Given two trees, return true if they are
structurally identical */
int identicalTrees(node* a, node* b)
{
    /*1. both empty */
    if (a == NULL && b == NULL)
        return 1;
 
    /* 2. both non-empty -> compare them */
    if (a != NULL && b != NULL) {
        return (a->data == b->data
                && identicalTrees(a->left, b->left)
                && identicalTrees(a->right, b->right));
    }
 
    /* 3. one empty, one not -> false */
    return 0;
}
 
/* Driver code*/
int main()
{
    node* root1 = newNode(1);
    node* root2 = newNode(1);
    root1->left = newNode(2);
    root1->right = newNode(3);
    root1->left->left = newNode(4);
    root1->left->right = newNode(5);
 
    root2->left = newNode(2);
    root2->right = newNode(3);
    root2->left->left = newNode(4);
    root2->left->right = newNode(5);
 
      // Function call
    if (identicalTrees(root1, root2))
        cout << "Both trees are identical.";
    else
        cout << "Trees are not identical.";
 
    return 0;
}
 
// This code is contributed by rathbhupendra

C




#include <stdio.h>
#include <stdlib.h>
 
/* A binary tree node has data, pointer to left child
   and a pointer to right child */
struct node {
    int data;
    struct node* left;
    struct node* right;
};
 
/* Helper function that allocates a new node with the
   given data and NULL left and right pointers. */
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);
}
 
/* Given two trees, return true if they are
 structurally identical */
int identicalTrees(struct node* a, struct node* b)
{
    /*1. both empty */
    if (a == NULL && b == NULL)
        return 1;
 
    /* 2. both non-empty -> compare them */
    if (a != NULL && b != NULL) {
        return (a->data == b->data
                && identicalTrees(a->left, b->left)
                && identicalTrees(a->right, b->right));
    }
 
    /* 3. one empty, one not -> false */
    return 0;
}
 
/* Driver code*/
int main()
{
    struct node* root1 = newNode(1);
    struct node* root2 = newNode(1);
    root1->left = newNode(2);
    root1->right = newNode(3);
    root1->left->left = newNode(4);
    root1->left->right = newNode(5);
 
    root2->left = newNode(2);
    root2->right = newNode(3);
    root2->left->left = newNode(4);
    root2->left->right = newNode(5);
 
      // Function call
    if (identicalTrees(root1, root2))
        printf("Both tree are identical.");
    else
        printf("Trees are not identical.");
 
    getchar();
    return 0;
}

Java




// Java program to see if two trees are identical
 
// A binary tree node
class Node {
    int data;
    Node left, right;
 
    Node(int item)
    {
        data = item;
        left = right = null;
    }
}
 
class BinaryTree {
    Node root1, root2;
 
    /* Given two trees, return true if they are
       structurally identical */
    boolean identicalTrees(Node a, Node b)
    {
        /*1. both empty */
        if (a == null && b == null)
            return true;
 
        /* 2. both non-empty -> compare them */
        if (a != null && b != null)
            return (a.data == b.data
                    && identicalTrees(a.left, b.left)
                    && identicalTrees(a.right, b.right));
 
        /* 3. one empty, one not -> false */
        return false;
    }
 
    /* Driver code*/
    public static void main(String[] args)
    {
        BinaryTree tree = new BinaryTree();
 
        tree.root1 = new Node(1);
        tree.root1.left = new Node(2);
        tree.root1.right = new Node(3);
        tree.root1.left.left = new Node(4);
        tree.root1.left.right = new Node(5);
 
        tree.root2 = new Node(1);
        tree.root2.left = new Node(2);
        tree.root2.right = new Node(3);
        tree.root2.left.left = new Node(4);
        tree.root2.left.right = new Node(5);
 
          // Function call
        if (tree.identicalTrees(tree.root1, tree.root2))
            System.out.println("Both trees are identical");
        else
            System.out.println("Trees are not identical");
    }
}

Python3




# Python3 program to determine if two trees are identical
 
# A binary tree node has data, pointer to left child
# and a pointer to right child
 
 
class Node:
    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
 
# Given two trees, return true if they are structurally
# identical
def identicalTrees(a, b):
 
    # 1. Both empty
    if a is None and b is None:
        return True
 
    # 2. Both non-empty -> Compare them
    if a is not None and b is not None:
        return ((a.data == b.data) and
                identicalTrees(a.left, b.left)and
                identicalTrees(a.right, b.right))
 
    # 3. one empty, one not -- false
    return False
 
 
# Driver code
root1 = Node(1)
root2 = Node(1)
root1.left = Node(2)
root1.right = Node(3)
root1.left.left = Node(4)
root1.left.right = Node(5)
 
root2.left = Node(2)
root2.right = Node(3)
root2.left.left = Node(4)
root2.left.right = Node(5)
 
# Function call
if __name__ == "__main__":
  if identicalTrees(root1, root2):
      print("Both trees are identical")
  else:
      print("Trees are not identical")
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)

C#




// C# program to see if two trees are identical
using System;
 
// C# program to see if two trees are identical
 
// A binary tree node
public class Node {
    public int data;
    public Node left, right;
 
    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}
 
public class BinaryTree {
    public Node root1, root2;
 
    /* Given two trees, return true if they are
       structurally identical */
    public virtual bool identicalTrees(Node a, Node b)
    {
        /*1. both empty */
        if (a == null && b == null) {
            return true;
        }
 
        /* 2. both non-empty -> compare them */
        if (a != null && b != null) {
            return (a.data == b.data
                    && identicalTrees(a.left, b.left)
                    && identicalTrees(a.right, b.right));
        }
 
        /* 3. one empty, one not -> false */
        return false;
    }
 
    /* Driver program to test identicalTrees() function */
    public static void Main(string[] args)
    {
        BinaryTree tree = new BinaryTree();
 
        tree.root1 = new Node(1);
        tree.root1.left = new Node(2);
        tree.root1.right = new Node(3);
        tree.root1.left.left = new Node(4);
        tree.root1.left.right = new Node(5);
 
        tree.root2 = new Node(1);
        tree.root2.left = new Node(2);
        tree.root2.right = new Node(3);
        tree.root2.left.left = new Node(4);
        tree.root2.left.right = new Node(5);
 
          // Function call
        if (tree.identicalTrees(tree.root1, tree.root2)) {
            Console.WriteLine("Both trees are identical");
        }
        else {
            Console.WriteLine("Trees are not identical");
        }
    }
}
 
// This code is contributed by Shrikant13

Javascript




<script>
 
    // JavaScript program to see if two trees are identical
     
    class Node
    {
        constructor(data) {
           this.left = null;
           this.right = null;
           this.data = data;
        }
    }
     
    let root1, root2;
    
    /* Given two trees, return true if they are
       structurally identical */
    function identicalTrees(a, b)
    {
        /*1. both empty */
        if (a == null && b == null)
            return true;
               
        /* 2. both non-empty -> compare them */
        if (a != null && b != null)
            return (a.data == b.data
                    && identicalTrees(a.left, b.left)
                    && identicalTrees(a.right, b.right));
    
        /* 3. one empty, one not -> false */
        return false;
    }
    
    root1 = new Node(1);
    root1.left = new Node(2);
    root1.right = new Node(3);
    root1.left.left = new Node(4);
    root1.left.right = new Node(5);
 
    root2 = new Node(1);
    root2.left = new Node(2);
    root2.right = new Node(3);
    root2.left.left = new Node(4);
    root2.left.right = new Node(5);
 
    if (identicalTrees(root1, root2))
      document.write("Both trees are identical");
    else
      document.write("Trees are not identical");
     
</script>

Output

Both trees are identical.

Time Complexity: O(min(N, M)), Where N and M are the sizes of the trees
Auxiliary Space: O(log min(N, M)), due to auxiliary stack space used by recursion calls

Write a function to determine if two trees are identical or not by comparing their traversals:

To solve the problem follow the below idea:

If two trees are identical, their preorder, inorder and postorder traversals will also be the same

Note: For this, we can find one traversal, say inorder, and if it is the same for both the trees, can we say the given trees are identical?  No, because we can have two trees with the same inorder traversal, still they can be non-identical.

See the below example:

Tree 1:    2                           Tree 2:   1
            /                                            \
         1                                                2

Both the trees have inorder traversal as “2  1”, but they are not identical.

To tackle such edge cases, we should find all the traversal for both the trees and see if they are equal. If yes, the given trees are identical else not.

Below is the implementation of this approach:

Java




/* java code to check if two trees are identical */
 
import java.io.*;
import java.util.*;
 
public class GFG {
 
    /* A binary tree node */
    static class Node {
        int data;
        Node left, right;
        public Node(int data) { this.data = data; }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        Node root1 = new Node(1);
        root1.left = new Node(2);
        root1.right = new Node(3);
        root1.left.left = new Node(4);
        root1.left.right = new Node(5);
 
        Node root2 = new Node(1);
        root2.left = new Node(2);
        root2.right = new Node(3);
        root2.left.left = new Node(4);
        root2.left.right = new Node(5);
 
          // Function call
        if (isIdentical(root1, root2)) {
            System.out.println(
                "Both the trees are identical.");
        }
        else {
            System.out.println(
                "Given trees are not identical.");
        }
    }
 
    // Function to check if two trees are identical
    static boolean isIdentical(Node root1, Node root2)
    {
        // Code Here
        // Create two arraylist 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 arraylist
        res1.clear();
        res2.clear();
        // check PreOrder
        preOrder(root1, res1);
        preOrder(root2, res2);
        if (!res1.equals(res2))
            return false;
 
        // clear previous result to reuse arraylist
        res1.clear();
        res2.clear();
        // check PostOrder
        postOrder(root1, res1);
        postOrder(root2, res2);
        if (!res1.equals(res2))
            return false;
 
        return true;
    }
 
    // Utility 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);
    }
 
    // Utility 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);
    }
 
    // Utility 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);
    }
}

Output

Both the trees are identical.

Time complexity: O(N)
Auxiliary Space: O(N), since using auxiliary ArrayList and call stack

Related Article: Iterative function to check if two trees are identical.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!