Write an efficient algorithm to check if two binary trees are identical or not. Two binary trees are identical if they have identical structure and their contents are also the same.

Input:
           1                        1
        /     \                  /     \
       2       3                2       3
     /   \   /   \            /   \   /   \
    4     5 6     7          4     5 6     7
 
Output: True
Explanation: Both binary trees have the same structure and contents.
 
Input:
           1                        1
        /     \                  /     \
       2       3                2       3
     /   \   /   \            /   \   /
    4     5 6     7          4     5 6
 
Output: False
Explanation: Both binary trees have different structures.
 
Input:
           1                        1
        /     \                  /     \
       2       3                2       3
     /   \   /   \            /   \   /   \
    4     5 6     7          4     5 6     8
 
Output: False
Explanation: Both binary trees have the same structure but differ in nodes’ values.

Practice this problem

Recursive Solution

The idea is to traverse both trees and compare values at their root node. If the value matches, recursively check if the first tree’s left subtree is identical to the left subtree of the second tree and the right subtree of the first tree is identical to the right subtree of the second tree. If the value at their root node differs, the trees violate data property. If at any point in the recursion, the first tree is empty and the second tree is non-empty, or the second tree is empty and the first tree is non-empty, the trees violate structural property, and they cannot be identical.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The given binary trees are identical

Java


Download  Run Code

Output:

The given binary trees are identical

Python


Download  Run Code

Output:

The given binary trees are identical

Iterative Solution

In an iterative version, we use the stack data structure similar to the implicit recursive stack. The implementation can be seen below in C++, Java, and Python:

C++


Download  Run Code

Output:

The given binary trees are identical

Java


Download  Run Code

Output:

The given binary trees are identical

Python


Download  Run Code

Output:

The given binary trees are identical

The time and space complexity of both recursive and iterative solutions are linear in terms of the total number of nodes in two trees. The space used by the recursive routine is also proportional to the tree’s height, whereas the iterative version use O(n) space for the stack data structure.