Open In App

Program to Determine if given Two Trees are Identical or not

Last Updated : 24 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two binary trees, the task is to find if both of them 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:

Program-to-Determine-if-given-Two-Trees-are-Identical-or-not-1

Output: Yes
Explanation: Trees are identical.

Input:      

Program-to-Determine-if-given-Two-Trees-are-Identical-or-not-2

Output: No
Explanation: Trees are not identical.

[Expected Approach – 1] Using DFS – O(n) Time and O(n) Space

The idea is to compare the root nodes’ data and recursively verify that their left and right subtrees are identical. Both trees must have the same structure and data at each corresponding node.

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 (r1->data == r2->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 the above approach:

C++
// C++ program to see if two trees are identical
// using DFS
#include <bits/stdc++.h>
using namespace std;

struct Node {
    int data;
    Node *left, *right;
  
    Node(int val) {
        data = val;
        left = right = nullptr;
    }
};

// Function to check if two trees are identical
bool isIdentical(Node* r1, Node* r2) {

    // If both trees are empty, they are identical
    if (r1 == nullptr && r2 == nullptr)
        return true;

    // If only one tree is empty, they are not identical
    if (r1 == nullptr || r2 == nullptr)
        return false;

    // Check if the root data is the same and
    // recursively check for the left and right subtrees
    return (r1->data == r2->data) &&
           isIdentical(r1->left, r2->left) &&
           isIdentical(r1->right, r2->right);
}

int main() {

    // Representation of input binary tree 1
    //        1
    //       / \
    //      2   3
    //     /
    //    4
    Node* r1 = new Node(1);    
    r1->left = new Node(2);   
    r1->right = new Node(3); 
    r1->left->left = new Node(4); 

    // Representation of input binary tree 2
    //        1
    //       / \
    //      2   3
    //     /
    //    4
    Node* r2 = new Node(1);    
    r2->left = new Node(2);   
    r2->right = new Node(3);  
    r2->left->left = new Node(4);

    if (isIdentical(r1, r2))
        cout << "Yes\n";
    else
        cout << "No\n";

    return 0;
}
C
// C program to see if two trees are identical
// using DFS
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *left, *right;
};

// Function to check if two trees are identical
bool isIdentical(struct Node* r1, struct Node* r2) {

    // If both trees are empty, they are identical
    if (r1 == NULL && r2 == NULL)
        return true;

    // If only one tree is empty, they are not identical
    if (r1 == NULL || r2 == NULL)
        return false;

    // Check if the root data is the same and
    // recursively check for the left and right subtrees
    return (r1->data == r2->data) &&
           isIdentical(r1->left, r2->left) &&
           isIdentical(r1->right, r2->right);
}

struct Node* createNode(int val) {
    struct Node *newNode 
      = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = val;
    newNode->left = newNode->right = NULL;
    return newNode;
}

int main() {

    // Representation of input binary tree 1
    //        1
    //       / \
    //      2   3
    //     /
    //    4
    struct Node *r1 = createNode(1);
    r1->left = createNode(2);
    r1->right = createNode(3);
    r1->left->left = createNode(4);

    // Representation of input binary tree 2
    //        1
    //       / \
    //      2   3
    //     /
    //    4
    struct Node *r2 = createNode(1);
    r2->left = createNode(2);
    r2->right = createNode(3);
    r2->left->left = createNode(4);

    if (isIdentical(r1, r2))
        printf("Yes\n");
    else
        printf("No\n");

    return 0;
}
Java
// Java program to see if two trees are identical
// using DFS
class Node {
    int data;
    Node left, right;

    Node(int val) {
        data = val;
        left = right = null;
    }
}

class GfG {

    // Function to check if two trees are identical
    static boolean isIdentical(Node r1, Node r2) {

        // If both trees are empty, they are identical
        if (r1 == null && r2 == null)
            return true;

        // If only one tree is empty, they are not identical
        if (r1 == null || r2 == null)
            return false;

        // Check if the root data is the same and
        // recursively check for the left and right subtrees
        return (r1.data == r2.data) &&
               isIdentical(r1.left, r2.left) &&
               isIdentical(r1.right, r2.right);
    }

    public static void main(String[] args) {

        // Representation of input binary tree 1
        //        1
        //       / \
        //      2   3
        //     /
        //    4
        Node r1 = new Node(1);
        r1.left = new Node(2);
        r1.right = new Node(3);
        r1.left.left = new Node(4);

        // Representation of input binary tree 2
        //        1
        //       / \
        //      2   3
        //     /
        //    4
        Node r2 = new Node(1);
        r2.left = new Node(2);
        r2.right = new Node(3);
        r2.left.left = new Node(4);

        if (isIdentical(r1, r2))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
Python
# Python program to see if two trees are identical
# using DFS
class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None

# Function to check if two trees are identical
def isIdentical(r1, r2):

    # If both trees are empty, they are identical
    if r1 is None and r2 is None:
        return True

    # If only one tree is empty, they are not identical
    if r1 is None or r2 is None:
        return False

    # Check if the root data is the same and
    # recursively check for the left and right subtrees
    return (r1.data == r2.data and
            isIdentical(r1.left, r2.left) and
            isIdentical(r1.right, r2.right))

if __name__ == "__main__":

    # Representation of input binary tree 1
    #        1
    #       / \
    #      2   3
    #     /
    #    4
    r1 = Node(1)
    r1.left = Node(2)
    r1.right = Node(3)
    r1.left.left = Node(4)

    # Representation of input binary tree 2
    #        1
    #       / \
    #      2   3
    #     /
    #    4
    r2 = Node(1)
    r2.left = Node(2)
    r2.right = Node(3)
    r2.left.left = Node(4)

    if isIdentical(r1, r2):
        print("Yes")
    else:
        print("No")
C#
// C# program to see if two trees are identical
// using DFS
using System;

class Node {
    public int Data;
    public Node left, right;

    public Node(int val) {
        Data = val;
        left = right = null;
    }
}

class GfG {

    // Function to check if two trees are identical
    static bool isIdentical(Node r1, Node r2) {

        // If both trees are empty, they are identical
        if (r1 == null && r2 == null)
            return true;

        // If only one tree is empty, they are not identical
        if (r1 == null || r2 == null)
            return false;

        // Check if the root data is the same and
        // recursively check for the left and right subtrees
        return (r1.Data == r2.Data) &&
               isIdentical(r1.left, r2.left) &&
               isIdentical(r1.right, r2.right);
    }

    static void Main(string[] args) {

        // Representation of input binary tree 1
        //        1
        //       / \
        //      2   3
        //     /
        //    4
        Node r1 = new Node(1);
        r1.left = new Node(2);
        r1.right = new Node(3);
        r1.left.left = new Node(4);

        // Representation of input binary tree 2
        //        1
        //       / \
        //      2   3
        //     /
        //    4
        Node r2 = new Node(1);
        r2.left = new Node(2);
        r2.right = new Node(3);
        r2.left.left = new Node(4);

        if (isIdentical(r1, r2))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
JavaScript
// Javascript program to see if two trees are identical
// using DFS
class Node {
    constructor(val) {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

// Function to check if two trees are identical
function isIdentical(r1, r2) {

    // If both trees are empty, they are identical
    if (r1 === null && r2 === null)
        return true;

    // If only one tree is empty, they are not identical
    if (r1 === null || r2 === null)
        return false;

    // Check if the root data is the same and
    // recursively check for the left and right subtrees
    return (r1.data === r2.data &&
            isIdentical(r1.left, r2.left) &&
            isIdentical(r1.right, r2.right));
}

// Representation of input binary tree 1
//        1
//       / \
//      2   3
//     /
//    4
let r1 = new Node(1);
r1.left = new Node(2);
r1.right = new Node(3);
r1.left.left = new Node(4);

// Representation of input binary tree 2
//        1
//       / \
//      2   3
//     /
//    4
let r2 = new Node(1);
r2.left = new Node(2);
r2.right = new Node(3);
r2.left.left = new Node(4);

if (isIdentical(r1, r2)) {
    console.log("Yes");
} 
else {
    console.log("No");
}

Output
Yes

Time Complexity: O(n), where n is the number of nodes in the larger of the two trees, as each node is visited once.
Auxiliary Space: O(h), where h is the height of the trees, due to the recursive call stack.

[Expected Approach – 2] Using Level Order Traversal (BFS) – O(n) Time and O(n) Space

The idea is to use level order traversal with two queues to compare the structure and data of two trees. By enqueuing nodes from both trees simultaneously, we can compare corresponding nodes at each level. If nodes at any level differ in data or structure, or if one tree has nodes where the other does not, the trees are not identical. This approach ensures that the trees are identical in both structure and node values if all nodes match and the queues are empty at the end.

Follow the below steps to implement the above idea:

  • Enqueue the root nodes of both trees into a queue.
  • While the queue is not empty, dequeue the front nodes of both trees and compare their values.
  • If the values are not equal, return false.
  • If the values are equal, enqueue the left and right child nodes of both trees, if they exist, into the queue.
  • Repeat steps 2-4 until either the queue becomes empty or we find two nodes with unequal values.
  • If the queue becomes empty and we have not found any nodes with unequal values, return true indicating that the trees are identical.

Below is the implementation of the above approach:

C++
// C++ program to see if two trees are identical
// using Level Order Traversal(BFS)
#include <bits/stdc++.h>
using namespace std;

struct Node {
    int data;
    Node *left, *right;
  
    Node(int val) {
        data = val;
        left = right = nullptr;
    }
};

// Function to check if two trees are identical 
// using level order traversal
bool isIdentical(Node* r1, Node* r2) {
    if (r1 == nullptr && r2 == nullptr)
        return true;

    if (r1 == nullptr || r2 == nullptr)
        return false;

    // Use two queues for level order traversal
    queue<Node*> q1, q2;
    q1.push(r1);
    q2.push(r2);

    while (!q1.empty() && !q2.empty()) {
        Node* node1 = q1.front();
        Node* node2 = q2.front();
        q1.pop();
        q2.pop();

        // Check if the current nodes are identical
        if (node1->data != node2->data)
            return false;

        // Check the left children
        if (node1->left && node2->left) {
            q1.push(node1->left);
            q2.push(node2->left);
        } else if (node1->left || node2->left) {
            return false;
        }

        // Check the right children
        if (node1->right && node2->right) {
            q1.push(node1->right);
            q2.push(node2->right);
        } else if (node1->right || node2->right) {
            return false;
        }
    }

    // If both queues are empty, the trees are identical
    return q1.empty() && q2.empty();
}

int main() {

    // Representation of input binary tree 1
    //        1
    //       / \
    //      2   3
    //     /
    //    4
    Node* r1 = new Node(1);    
    r1->left = new Node(2);   
    r1->right = new Node(3); 
    r1->left->left = new Node(4); 

    // Representation of input binary tree 2
    //        1
    //       / \
    //      2   3
    //     /
    //    4
    Node* r2 = new Node(1);    
    r2->left = new Node(2);   
    r2->right = new Node(3);  
    r2->left->left = new Node(4);

    if (isIdentical(r1, r2))
        cout << "Yes\n";
    else
        cout << "No\n";

    return 0;
}
Java
// Java program to see if two trees are identical
// using Level Order Traversal(BFS)
import java.util.LinkedList;
import java.util.Queue;

class Node {
    int data;
    Node left, right;

    Node(int val) {
        data = val;
        left = right = null;
    }
}

class GfG {

    // Function to check if two trees are identical
    // using level-order traversal
    static boolean isIdentical(Node r1, Node r2) {

        // If both trees are empty, they are identical
        if (r1 == null && r2 == null)
            return true;

        // If one tree is empty and the other is not
        if (r1 == null || r2 == null)
            return false;

        // Queues to store nodes for level-order traversal
        Queue<Node> q1 = new LinkedList<>();
        Queue<Node> q2 = new LinkedList<>();

        q1.add(r1);
        q2.add(r2);

        // Perform level-order traversal for both trees
        while (!q1.isEmpty() && !q2.isEmpty()) {

            Node n1 = q1.poll();
            Node n2 = q2.poll();

            // Check if the current nodes are not equal
            if (n1.data != n2.data)
                return false;

            // Check left children
            if (n1.left != null && n2.left != null) {
                q1.add(n1.left);
                q2.add(n2.left);
            } 
            else if (n1.left != null || n2.left != null) {
                return false;
            }

            // Check right children
            if (n1.right != null && n2.right != null) {
                q1.add(n1.right);
                q2.add(n2.right);
            } 
            else if (n1.right != null || n2.right != null) {
                return false;
            }
        }

        // Both queues should be empty if trees are identical
        return q1.isEmpty() && q2.isEmpty();
    }

    public static void main(String[] args) {

        // Representation of input binary tree 1
        //        1
        //       / \
        //      2   3
        //     /
        //    4
        Node r1 = new Node(1);
        r1.left = new Node(2);
        r1.right = new Node(3);
        r1.left.left = new Node(4);

        // Representation of input binary tree 2
        //        1
        //       / \
        //      2   3
        //     /
        //    4
        Node r2 = new Node(1);
        r2.left = new Node(2);
        r2.right = new Node(3);
        r2.left.left = new Node(4);

        if (isIdentical(r1, r2))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
Python
# Python program to see if two trees are identical
# using Level Order Traversal(BFS)
from collections import deque

class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None

# Function to check if two trees are identical 
# using level-order traversal
def isIdentical(r1, r2):

    # If both trees are empty, they are identical
    if r1 is None and r2 is None:
        return True

    # If one tree is empty and the other is not
    if r1 is None or r2 is None:
        return False

    # Queues for level-order traversal
    q1 = deque([r1])
    q2 = deque([r2])

    # Perform level-order traversal for both trees
    while q1 and q2:

        n1 = q1.popleft()
        n2 = q2.popleft()

        # Check if the current nodes are not equal
        if n1.data != n2.data:
            return False

        # Check left children
        if n1.left and n2.left:
            q1.append(n1.left)
            q2.append(n2.left)
            
        elif n1.left or n2.left:
            return False

        # Check right children
        if n1.right and n2.right:
            q1.append(n1.right)
            q2.append(n2.right)
            
        elif n1.right or n2.right:
            return False

    # Both queues should be empty if trees are identical
    return not q1 and not q2

if __name__ == "__main__":

    # Representation of input binary tree 1
    #        1
    #       / \
    #      2   3
    #     /
    #    4
    r1 = Node(1)
    r1.left = Node(2)
    r1.right = Node(3)
    r1.left.left = Node(4)

    # Representation of input binary tree 2
    #        1
    #       / \
    #      2   3
    #     /
    #    4
    r2 = Node(1)
    r2.left = Node(2)
    r2.right = Node(3)
    r2.left.left = Node(4)

    if isIdentical(r1, r2):
        print("Yes")
    else:
        print("No")
C#
// C# program to see if two trees are identical
// using Level Order Traversal(BFS)
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;

    public Node(int val) {
        data = val;
        left = right = null;
    }
}

class GfG {

    // Function to check if two trees are identical 
    // using level-order traversal
    static bool IsIdentical(Node r1, Node r2) {

        // If both trees are empty, they are identical
        if (r1 == null && r2 == null)
            return true;

        // If one tree is empty and the other is not
        if (r1 == null || r2 == null)
            return false;

        // Queues for level-order traversal
        Queue<Node> q1 = new Queue<Node>();
        Queue<Node> q2 = new Queue<Node>();

        q1.Enqueue(r1);
        q2.Enqueue(r2);

        // Perform level-order traversal for both trees
        while (q1.Count > 0 && q2.Count > 0) {
            Node n1 = q1.Dequeue();
            Node n2 = q2.Dequeue();

            // Check if the current nodes' data are not equal
            if (n1.data != n2.data)
                return false;

            // Check left children
            if (n1.left != null && n2.left != null) {
                q1.Enqueue(n1.left);
                q2.Enqueue(n2.left);
            } 
            else if (n1.left != null || n2.left != null) {
                return false;
            }

            // Check right children
            if (n1.right != null && n2.right != null) {
                q1.Enqueue(n1.right);
                q2.Enqueue(n2.right);
            } 
            else if (n1.right != null || n2.right != null) {
                return false;
            }
        }

        // Both queues should be empty if trees are 
        // identical
        return q1.Count == 0 && q2.Count == 0;
    }

    static void Main(string[] args) {

        // Representation of input binary tree 1
        //        1
        //       / \
        //      2   3
        //     /
        //    4
        Node r1 = new Node(1);
        r1.left = new Node(2);
        r1.right = new Node(3);
        r1.left.left = new Node(4);

        // Representation of input binary tree 2
        //        1
        //       / \
        //      2   3
        //     /
        //    4
        Node r2 = new Node(1);
        r2.left = new Node(2);
        r2.right = new Node(3);
        r2.left.left = new Node(4);

        if (IsIdentical(r1, r2))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
JavaScript
// Javascript program to see if two trees are identical
// using Level Order Traversal(BFS)
class Node {
    constructor(val) {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

// Function to check if two trees are identical
// using level-order traversal
function isIdentical(r1, r2) {

    // If both trees are empty, they are identical
    if (r1 === null && r2 === null)
        return true;

    // If one tree is empty and the other is not
    if (r1 === null || r2 === null)
        return false;

    // Queues for level-order traversal
    let queue1 = [r1];
    let queue2 = [r2];

    // Perform level-order traversal for both trees
    while (queue1.length > 0 && queue2.length > 0) {
        let node1 = queue1.shift();
        let node2 = queue2.shift();

        // Check if the current nodes' data are not equal
        if (node1.data !== node2.data)
            return false;

        // Check left children
        if (node1.left && node2.left) {
            queue1.push(node1.left);
            queue2.push(node2.left);
        } 
        else if (node1.left || node2.left) {
            return false;
        }

        // Check right children
        if (node1.right && node2.right) {
            queue1.push(node1.right);
            queue2.push(node2.right);
        } 
        else if (node1.right || node2.right) {
            return false;
        }
    }

    // Both queues should be empty if trees are identical
    return queue1.length === 0 && queue2.length === 0;
}

// Representation of input binary tree 1
//        1
//       / \
//      2   3
//     /
//    4
let r1 = new Node(1);
r1.left = new Node(2);
r1.right = new Node(3);
r1.left.left = new Node(4);

// Representation of input binary tree 2
//        1
//       / \
//      2   3
//     /
//    4
let r2 = new Node(1);
r2.left = new Node(2);
r2.right = new Node(3);
r2.left.left = new Node(4);

if (isIdentical(r1, r2)) {
    console.log("Yes");
} 
else {
    console.log("No");
}

Output
Yes

Time complexity: O(n), where n is the number of nodes in the larger of the two trees, as each node is visited once.
Auxiliary Space: O(w), where w is the maximum width of the trees at any level, due to the space required for the queues.

[Expected Approach – 3] Using Morris Traversal – O(n) Time and O(1) Space

The idea is to use Morris traversal for comparing two trees, traverse both trees simultaneously by starting at their roots. For each node, if the left subtree exists, find the rightmost node in the left subtree (the predecessor) and create a temporary link back to the current node. Then, move to the left subtree. If no left subtree exists, compare the current nodes of both trees and move to the right subtree. At each step, compare the values of the corresponding nodes and ensure the structure matches. If at any point the values or structure differ, the trees are not identical. The process continues until both trees are fully traversed, and any temporary links created are removed. If no mismatches are found, the trees are identical.

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 approach:

C++
// C++ program to see if two trees are identical
// using Morris Traversal
#include <bits/stdc++.h>
using namespace std;

struct Node {
    int data;
    Node *left, *right;

    Node(int val) {
        data = val;
        left = right = nullptr;
    }
};

// Function to check if two trees are 
// identical using Morris traversal
bool isIdentical(Node* r1, Node* r2) {

    // Check if both trees are empty
    if (r1 == nullptr && r2 == nullptr)
        return true;

    // Check if one tree is empty and the other is not
    if (r1 == nullptr || r2 == nullptr)
        return false;

    // Morris traversal to compare both trees
    while (r1 != nullptr && r2 != nullptr) {

        // Compare the data of both current nodes
        if (r1->data != r2->data)
            return false;

        // Morris traversal for the first tree (r1)
        if (r1->left == nullptr) {
            
            // Move to the right child if no left child
            r1 = r1->right;
        } else {
            
            // Find the inorder predecessor of r1
            Node* pre = r1->left;
            while (pre->right != nullptr
                && pre->right != r1) {
                pre = pre->right;
            }

            // Set the temporary link to r1
            if (pre->right == nullptr) {
                pre->right = r1;
                r1 = r1->left;
            } 
          
            // Remove the temporary link and move to right
            else {
                pre->right = nullptr;
                r1 = r1->right;
            }
        }

        // Morris traversal for the second tree (r2)
        if (r2->left == nullptr) {
            
            // Move to the right child if no left child
            r2 = r2->right;
        } else {
            
            // Find the inorder predecessor of r2
            Node* pre = r2->left;
            while (pre->right != nullptr
                && pre->right != r2) {
                pre = pre->right;
            }

            // Set the temporary link to r2
            if (pre->right == nullptr) {
                pre->right = r2;
                r2 = r2->left;
            } 
          
            // Remove the temporary link and move to right
            else {
                pre->right = nullptr;
                r2 = r2->right;
            }
        }
    }

    // Both trees are identical if both are null at end
    return (r1 == nullptr && r2 == nullptr);
}

int main() {

    // Representation of input binary tree 1
    //        1
    //       / \
    //      2   3
    //     /
    //    4
    Node* r1 = new Node(1);
    r1->left = new Node(2);
    r1->right = new Node(3);
    r1->left->left = new Node(4);

    // Representation of input binary tree 2
    //        1
    //       / \
    //      2   3
    //     /
    //    4
    Node* r2 = new Node(1);
    r2->left = new Node(2);
    r2->right = new Node(3);
    r2->left->left = new Node(4);

    if (isIdentical(r1, r2))
        cout << "Yes\n";
    else
        cout << "No\n";

    return 0;
}
C
// C program to see if two trees are identical
// using Morris Traversal
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *left, *right;
};

// Function to check if two trees are identical 
// using Morris traversal
int isIdentical(struct Node* r1, struct Node* r2) {

    // Check if both trees are empty
    if (r1 == NULL && r2 == NULL)
        return 1;

    // Check if one tree is empty and the other is not
    if (r1 == NULL || r2 == NULL)
        return 0;

    // Morris traversal to compare both trees
    while (r1 != NULL && r2 != NULL) {

        // Compare the data of both current nodes
        if (r1->data != r2->data)
            return 0;

        // Morris traversal for the first tree (r1)
        if (r1->left == NULL) {
          
            // Move to the right child if no left child
            r1 = r1->right;
        } else {
          
            // Find the inorder predecessor of r1
            struct Node* pre = r1->left;
            while (pre->right != NULL && pre->right != r1) {
                pre = pre->right;
            }

            // Set the temporary link to r1
            if (pre->right == NULL) {
                pre->right = r1;
                r1 = r1->left;
            } 
          
            // Remove the temporary link and move to right
            else {
                pre->right = NULL;
                r1 = r1->right;
            }
        }

        // Morris traversal for the second tree (r2)
        if (r2->left == NULL) {
          
            // Move to the right child if no left child
            r2 = r2->right;
        } else {
          
            // Find the inorder predecessor of r2
            struct Node* pre = r2->left;
            while (pre->right != NULL && pre->right != r2) {
                pre = pre->right;
            }

            // Set the temporary link to r2
            if (pre->right == NULL) {
                pre->right = r2;
                r2 = r2->left;
            } 
          
            // Remove the temporary link and move to right
            else {
                pre->right = NULL;
                r2 = r2->right;
            }
        }
    }

    // Both trees are identical if both are 
    // null at the end
    return (r1 == NULL && r2 == NULL);
}

struct Node* createNode(int val) {
    struct Node* node
       = (struct Node*)malloc(sizeof(struct Node));
    node->data = val;
    node->left = node->right = NULL;
    return node;
}

int main() {

    // Representation of input binary tree 1
    //        1
    //       / \
    //      2   3
    //     /
    //    4
    struct Node* r1 = createNode(1);
    r1->left = createNode(2);
    r1->right = createNode(3);
    r1->left->left = createNode(4);

    // Representation of input binary tree 2
    //        1
    //       / \
    //      2   3
    //     /
    //    4
    struct Node* r2 = createNode(1);
    r2->left = createNode(2);
    r2->right = createNode(3);
    r2->left->left = createNode(4);

    if (isIdentical(r1, r2))
        printf("Yes\n");
    else
        printf("No\n");

    return 0;
}
Java
// Java program to see if two trees are identical
// using Morris Traversal
import java.util.*;

class Node {
    int data;
    Node left, right;

    Node(int val) {
        data = val;
        left = right = null;
    }
}

class GfG {

    // Function to check if two trees are identical
    // using Morris traversal
    static boolean isIdentical(Node r1, Node r2) {

        // Check if both trees are empty
        if (r1 == null && r2 == null)
            return true;

        // Check if one tree is empty and the other is not
        if (r1 == null || r2 == null)
            return false;

        // Morris traversal to compare both trees
        while (r1 != null && r2 != null) {

            // Compare the data of both current nodes
            if (r1.data != r2.data)
                return false;

            // Morris traversal for the first tree (r1)
            if (r1.left == null) {

                // Move to the right child if no left child
                r1 = r1.right;
            } 
            else {

                // Find the inorder predecessor of r1
                Node pre = r1.left;
                while (pre.right != null && pre.right != r1) {
                    pre = pre.right;
                }

                // Set the temporary link to r1
                if (pre.right == null) {
                    pre.right = r1;
                    r1 = r1.left;
                } 

                // Remove the temporary link and move to right
                else {
                    pre.right = null;
                    r1 = r1.right;
                }
            }

            // Morris traversal for the second tree (r2)
            if (r2.left == null) {

                // Move to the right child if no left child
                r2 = r2.right;
            } 
            else {

                // Find the inorder predecessor of r2
                Node pre = r2.left;
                while (pre.right != null && pre.right != r2) {
                    pre = pre.right;
                }

                // Set the temporary link to r2
                if (pre.right == null) {
                    pre.right = r2;
                    r2 = r2.left;
                } 

                // Remove the temporary link and move to right
                else {
                    pre.right = null;
                    r2 = r2.right;
                }
            }
        }

        // Both trees are identical if both are 
        // null at the end
        return (r1 == null && r2 == null);
    }

    public static void main(String[] args) {

        // Representation of input binary tree 1
        //        1
        //       / \
        //      2   3
        //     /
        //    4
        Node r1 = new Node(1);
        r1.left = new Node(2);
        r1.right = new Node(3);
        r1.left.left = new Node(4);

        // Representation of input binary tree 2
        //        1
        //       / \
        //      2   3
        //     /
        //    4
        Node r2 = new Node(1);
        r2.left = new Node(2);
        r2.right = new Node(3);
        r2.left.left = new Node(4);

        if (isIdentical(r1, r2))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
Python
# Python program to see if two trees are identical
# using Morris Traversal
class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None

# Function to check if two trees are identical 
# using Morris traversal
def isIdentical(r1, r2):

    # Check if both trees are empty
    if r1 is None and r2 is None:
        return True

    # Check if one tree is empty and the other is not
    if r1 is None or r2 is None:
        return False

    # Morris traversal to compare both trees
    while r1 is not None and r2 is not None:

        # Compare the data of both current nodes
        if r1.data != r2.data:
            return False

        # Morris traversal for the first tree (r1)
        if r1.left is None:

            # Move to the right child if no left child
            r1 = r1.right
        else:

            # Find the inorder predecessor of r1
            pre = r1.left
            while pre.right is not None and pre.right != r1:
                pre = pre.right

            # Set the temporary link to r1
            if pre.right is None:
                pre.right = r1
                r1 = r1.left

            # Remove the temporary link and move to right
            else:
                pre.right = None
                r1 = r1.right

        # Morris traversal for the second tree (r2)
        if r2.left is None:

            # Move to the right child if no left child
            r2 = r2.right
        else:

            # Find the inorder predecessor of r2
            pre = r2.left
            while pre.right is not None and pre.right != r2:
                pre = pre.right

            # Set the temporary link to r2
            if pre.right is None:
                pre.right = r2
                r2 = r2.left

            # Remove the temporary link and move to right
            else:
                pre.right = None
                r2 = r2.right

    # Both trees are identical if both are null at end
    return r1 is None and r2 is None

if __name__ == '__main__':
  
    # Representation of input binary tree 1
    #        1
    #       / \
    #      2   3
    #     /
    #    4
    r1 = Node(1)
    r1.left = Node(2)
    r1.right = Node(3)
    r1.left.left = Node(4)

    # Representation of input binary tree 2
    #        1
    #       / \
    #      2   3
    #     /
    #    4
    r2 = Node(1)
    r2.left = Node(2)
    r2.right = Node(3)
    r2.left.left = Node(4)

    if isIdentical(r1, r2):
        print("Yes")
    else:
        print("No")
C#
// C# program to see if two trees are identical
// using Morris Traversal
using System;

class Node {
    public int data;
    public Node left, right;
  
    public Node(int val) {
        data = val;
        left = right = null;
    }
}

class GfG {

    // Function to check if two trees are identical 
    // using Morris traversal
    static bool IsIdentical(Node r1, Node r2) {

        // Check if both trees are empty
        if (r1 == null && r2 == null)
            return true;

        // Check if one tree is empty and the other is not
        if (r1 == null || r2 == null)
            return false;

        // Morris traversal to compare both trees
        while (r1 != null && r2 != null) {

            // Compare the data of both current nodes
            if (r1.data != r2.data)
                return false;

            // Morris traversal for the first tree (r1)
            if (r1.left == null) {

                // Move to the right child if no left child
                r1 = r1.right;
            } 
            else {

                // Find the inorder predecessor of r1
                Node pre = r1.left;
                while (pre.right != null && pre.right != r1) {
                    pre = pre.right;
                }

                // Set the temporary link to r1
                if (pre.right == null) {
                    pre.right = r1;
                    r1 = r1.left;
                } 

                // Remove the temporary link and move to right
                else {
                    pre.right = null;
                    r1 = r1.right;
                }
            }

            // Morris traversal for the second tree (r2)
            if (r2.left == null) {

                // Move to the right child if no left child
                r2 = r2.right;
            } 
            else {

                // Find the inorder predecessor of r2
                Node pre = r2.left;
                while (pre.right != null && pre.right != r2) {
                    pre = pre.right;
                }

                // Set the temporary link to r2
                if (pre.right == null) {
                    pre.right = r2;
                    r2 = r2.left;
                } 

                // Remove the temporary link and move to right
                else {
                    pre.right = null;
                    r2 = r2.right;
                }
            }
        }

        // Both trees are identical if both are
        // null at end
        return (r1 == null && r2 == null);
    }

    static void Main(string[] args) {

        // Representation of input binary tree 1
        //        1
        //       / \
        //      2   3
        //     /
        //    4
        Node r1 = new Node(1);
        r1.left = new Node(2);
        r1.right = new Node(3);
        r1.left.left = new Node(4);

        // Representation of input binary tree 2
        //        1
        //       / \
        //      2   3
        //     /
        //    4
        Node r2 = new Node(1);
        r2.left = new Node(2);
        r2.right = new Node(3);
        r2.left.left = new Node(4);

        if (IsIdentical(r1, r2))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
JavaScript
// Javascript program to see if two trees are identical
// using Morris Traversal
class Node {
    constructor(val) {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

// Function to check if two trees are identical 
// using Morris traversal
function isIdentical(r1, r2) {

    // Check if both trees are empty
    if (r1 === null && r2 === null) {
        return true;
    }

    // Check if one tree is empty and the other is not
    if (r1 === null || r2 === null) {
        return false;
    }

    // Morris traversal to compare both trees
    while (r1 !== null && r2 !== null) {

        // Compare the data of both current nodes
        if (r1.data !== r2.data) {
            return false;
        }

        // Morris traversal for the first tree (r1)
        if (r1.left === null) {

            // Move to the right child if no left child
            r1 = r1.right;
        } 
        else {

            // Find the inorder predecessor of r1
            let pre = r1.left;
            while (pre.right !== null && pre.right !== r1) {
                pre = pre.right;
            }

            // Set the temporary link to r1
            if (pre.right === null) {
                pre.right = r1;
                r1 = r1.left;
            } 
            
            // Remove the temporary link and move to right
            else {
                pre.right = null;
                r1 = r1.right;
            }
        }

        // Morris traversal for the second tree (r2)
        if (r2.left === null) {

            // Move to the right child if no left child
            r2 = r2.right;
        } 
        else {

            // Find the inorder predecessor of r2
            let pre = r2.left;
            while (pre.right !== null && pre.right !== r2) {
                pre = pre.right;
            }

            // Set the temporary link to r2
            if (pre.right === null) {
                pre.right = r2;
                r2 = r2.left;
            } 
            
            // Remove the temporary link and move to right
            else {
                pre.right = null;
                r2 = r2.right;
            }
        }
    }

    // Both trees are identical if both are null at end
    return r1 === null && r2 === null;
}

// Representation of input binary tree 1
//        1
//       / \
//      2   3
//     /
//    4
let r1 = new Node(1);
r1.left = new Node(2);
r1.right = new Node(3);
r1.left.left = new Node(4);

// Representation of input binary tree 2
//        1
//       / \
//      2   3
//     /
//    4
let r2 = new Node(1);
r2.left = new Node(2);
r2.right = new Node(3);
r2.left.left = new Node(4);

if (isIdentical(r1, r2)) {
    console.log("Yes");
} 
else {
    console.log("No");
}

Output
Yes

Time Complexity: O(n), where n is the number of nodes in the larger of the two trees, as each node is visited once.
Auxiliary Space: O(1), Morris traversal modifies the tree temporarily by establishing “threads” to traverse nodes without using recursion or a stack.



Next Article
Article Tags :
Practice Tags :

Similar Reads