VOOZH about

URL: https://www.geeksforgeeks.org/dsa/potd-solutions-21-nov-23-determine-if-two-trees-are-identical/

⇱ POTD Solutions | 21 Nov' 23 | Determine if Two Trees are Identical - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

POTD Solutions | 21 Nov' 23 | Determine if Two Trees are Identical

Last Updated : 23 Jul, 2025

View all POTD Solutions

Welcome to the daily solutions of our . We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Binary Tree but will also help you build up problem-solving skills.

👁 21st-nov
POTD Solution 21 November 2023
We recommend you to try this problem on our GeeksforGeeks Practice portal first, and maintain your streak to earn Geeksbits and other exciting prizes, before moving towards the solution.

Given two binary trees, the task is to find if both of them are identical or not. Return true if they are identical, else return false.

Examples:

Input:        1                    1
                 /   \                /   \
               2      3            2      3
             /                    /
           4                   4
Output: Yes
Explanation: Both trees are identical as the have same root, left and right child.

Input:         1                    1
                 /   \                /   \
               2      3            5      3
                     /             /
                  4             4
Output: Trees are not identical

The basic idea behind the Morris traversal approach to solve the problem of checking if two binary trees are identical is to use the Morris traversal algorithm to traverse both trees in-order simultaneously, and compare the nodes visited at each step.

Follow the steps to implement the above idea:

  • Check if both trees are empty. If they are, return true. If only one of them is empty, return false.
  • Perform the Morris traversal for in-order traversal of both trees simultaneously. At each step, compare the nodes visited in both trees.
  • If at any step, the nodes visited in both trees are not equal, return false.
  • If we reach the end of both trees simultaneously (i.e., both nodes are NULL), return true.

Below is the implementation of the above idea:

Time Complexity: O(N), where N is the number of nodes in the binary tree
Auxiliary Space: O(1)


Comment
Article Tags: