Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Check Identical Trees

Moderate
0/80
Average time to solve is 20m
profile
Contributed by
59 upvotes
Asked in companies
MicrosoftDisney + HotstarHike

Problem statement

You are given two binary trees with 'n' and 'm' nodes respectively.


You need to return true if the two trees are identical. Otherwise, return false.


Example:
For the trees given below:- 

example

The given trees are identical as:-
1. The number of nodes in both trees is the same. 
2. The number of edges in both trees is the same. 
3. The data for root for both the trees is the same i.e 5. 
4. The data of root -> left (root’s left child) for both the trees is the same i.e 2.
5. The data of root -> right (root’s right child) for both the trees is the same i.e 3.
6. The data of root -> right -> left ( left child of root’s right child) for both the trees is the same i.e 6.
7. Nodes with data 2 and 6 are the leaf nodes for both the binary trees. 
Detailed explanation ( Input/output format, Notes, Images )
Input format :
The first line of input contains elements in the level order form for the first binary tree. The line consists of values of nodes separated by a single space. In case a node is null, we take -1 in its place.

The second line of input contains elements in the level order form for the second tree. The line consists of values of nodes separated by a single space. In case a node is null, we take -1 in its place.
Input format explanation:
The level order input for the tree depicted in the below image would be 

alt text

1
2 3
4 -1 5 6
-1 7 -1 -1 -1 -1
-1 -1

The sequence will be put together in a single line separated by a single space. Hence, for the above-depicted tree, the input will be given as:

1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1

Explanation :
Level 1 :
The root node of the tree is 1

Level 2 :
Left child of 1 = 2
Right child of 1 = 3

Level 3 :
Left child of 2 = 4
Right child of 2 = null (-1)
Left child of 3 = 5
Right child of 3 = 6

Level 4 :
Left child of 4 = null (-1)
Right child of 4 = 7
Left child of 5 = null (-1)
Right child of 5 = null (-1)
Left child of 6 = null (-1)
Right child of 6 = null (-1)

Level 5 :
Left child of 7 = null (-1)
Right child of 7 = null (-1)

The first not-null node (of the previous level) is treated as the parent of the first two nodes of the current level. The second not-null node (of the previous level) is treated as the parent node for the next two nodes of the current level, and so on.
The input ends when all nodes at the last level are null (-1).
Output format :
Print in a single line either “True” (if the two trees are identical) or “False” otherwise. 
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
Sample input 1 :
5 2 3 -1 6 -1 -1 -1 -1
5 2 3 -1 6 -1 -1 -1 -1
Sample output 1 :
True
Explanation for Sample Input 1 :
Refer to the example given above in the problem description.
Sample input 2 :
1 -1 2 -1 -1
1 2 -1 -1 -1  
Sample output 2 :
False
Explanation for Sample Input 2 :

example

Although the following conditions satisfy:

The number of nodes in both trees is the same.
The number of edges in both trees is the same. 
The data for root for both the trees is the same i.e 1.

It’s visible from the pictorial representation that the trees are not identical. Reason being:
In Binary tree 1, root’s right is NULL but it’s not true for Binary tree 2. 
In Binary tree 1, root’s left is not NULL but it’s not true for Binary tree 2. 
Expected time complexity:
The expected time complexity is O(min(n,m)).
Constraints :
0 <= 'n' <= 10^6
0 <= 'm' <= 10^6
1 <= Node Data <= 10^9 

Time limit: 1 sec
Hint

We can observe that the level order traversal for both the given trees will be the same if they are identical. We can thus store the level order traversal for both the trees and check if it is the same or not. 

Approaches (2)
BFS

The idea here is that we will store the level order traversal for both the trees in two lists and as the level order traversal for identical trees must be the same so we will check whether both the lists are the same or not. So the steps will be as given below.

 

  1. Maintain an array say levelOrderTree1 and store the level order traversal of Binary tree 1 taking NULL nodes as ‘-1’.
  2. Maintain an array say levelOrderTree2 and store the level order traversal of Binary tree 2 taking NULL nodes as ‘-1’.
  3. Check if the two arrays are identical or not. If any of the indexes from both arrays mismatch return false otherwise return true.
Time Complexity

O(max(M, N)) per test case where M and N are the number of nodes in Binary tree 1 and Binary tree 2 respectively.

 

In the worst case, for both the trees, we are traversing every node once.

Space Complexity

O(max(M, N)) per test case where M and N are the number of nodes in Binary tree 1 and Binary tree 2 respectively.

 

In the worst case, we are using extra space for creating arrays for the two trees.

Video Solution
Unlock at level 3
(75% EXP penalty)
Code Solution
(100% EXP penalty)
Check Identical Trees
All tags
Sort by
Search icon

Interview problems

✅Easy C++ & Java Solution|| Beginner's Friendly🔥🔥

Intuition :

 

We can simply solve this question using recursion. For this we have to declare the base case i.e. if(root1 == null && root2 == null) return true;

 

Approach :

 

1. Define Base Cases:

  • Both Trees are Empty: If both trees are null, they are identical. Return true.
  • One Tree is Empty: If one tree is null and the other is not, they cannot be identical. Return false.

2. Compare Current Nodes:

  • Check if the values of the current nodes in both trees are equal. If they are not, return false.

3. Recursive Checks:

  • If the current nodes are equal, recursively check:
    • Left Subtrees: Call the function on the left child of both trees.
    • Right Subtrees: Call the function on the right child of both trees.
  • Combine the results of these two recursive calls using a logical AND operator (&&). Both calls must return true for the trees to be considered identical.

4. Return Result:

  • If all checks are passed, return true. If any check fails, return false.

 

Pseudocode:


function areIdentical(tree1, tree2):
   if tree1 is NULL and tree2 is NULL:
       return true
   if tree1 is NULL or tree2 is NULL:
       return false
   if tree1.value != tree2.value:
       return false
   return areIdentical(tree1.left, tree2.left) AND
          areIdentical(tree1.right, tree2.right)

 

Code :

C++ Code

bool identicalTrees(BinaryTreeNode<int>* root1, BinaryTreeNode<int>* root2) {
    // Write your code here. 	
    if(root1==nullptr && root2==nullptr)return true;
    if(root1==nullptr || root2==nullptr)return false;

    return (root1->data == root2->data)&&
    identicalTrees(root1->left, root2->left)&&
    identicalTrees(root1->right, root2->right); 
}

Java Code :

public class Solution {
    public static boolean identicalTrees(BinaryTreeNode<Integer> root1, BinaryTreeNode<Integer> root2) {
        // Write you code here.
    if(root1==null && root2==null)return true;
    if(root1==null || root2==null)return false;

    return (root1.data == root2.data)&&
    identicalTrees(root1.left, root2.left)&&
    identicalTrees(root1.right, root2.right); 
    }
}
12 views
0 replies
1 upvote

Interview problems

Recursive solution in java || beats 78% of users

public class Solution {

    public static boolean identicalTrees(BinaryTreeNode<Integer> root1, BinaryTreeNode<Integer> root2) {

        // Write you code here.

 

        if(root1==null && root2==null) {

            return true;

        }

 

        if((root1!=null && root2==null) || (root1==null && root2!=null)) {

            return false;

        }

 

        if(root1.data != root2.data) {

            return false;

        }

 

        return identicalTrees(root1.left, root2.left) && identicalTrees(root1.right, root2.right);

    }

}

datastructures

java

programming

2 views
0 replies
1 upvote

Interview problems

Check Identical Trees Easy Solution

 

bool identicalTrees(BinaryTreeNode<int>* root1, BinaryTreeNode<int>* root2) {

    // Base case

    if(root1==NULL && root2==NULL){

        return true;

    }   

    if(root1!=NULL && root2==NULL){

        return false;

    }

    if(root1==NULL && root2!=NULL){

        return false;

    } 

 

    bool left=identicalTrees(root1->left,root2->left);

    bool right=identicalTrees(root1->right,root2->right);

 

    bool value=root1->data==root2->data;

    if(left && right && value){

        return true;

    }

    else{

        return false;

    }

}

28 views
0 replies
0 upvotes

Interview problems

C++ Solution || Better than 99.9%

bool identicalTrees(BinaryTreeNode<int>* root1, BinaryTreeNode<int>* root2) {

    //Base cases 

    if(root1==NULL && root2==NULL){

        return true;

    }    

 

    if(root1==NULL && root2!=NULL){

        return false;

    }

 

    if(root1!=NULL && root2==NULL){

        return false;

    }

 

    bool left = identicalTrees(root1->left, root2->left);

    bool right = identicalTrees(root1->right, root2->right);  

    bool val = root1->data==root2->data;

    if(left && right && val){

        return true;

    }

 

    else{

        return false;

    }

 

}

66 views
0 replies
0 upvotes

Interview problems

INSUFFICIENT TESTCASES!!!

bool identicalTrees(BinaryTreeNode<int>* root1, BinaryTreeNode<int>* root2) {
    if(root1 == NULL && root2 == NULL) return true;
    if(root1 == NULL || root2 == NULL) return false;
    return (
        identicalTrees(root1->left, root2->left) && 
        identicalTrees(root1->right, root2->right)
    );
}

 

This code just checks for the structure of the BT, not the node values, and all testcases passed????..

 

Please add more testcases CodeStudio!!!

16 views
0 replies
0 upvotes

Interview problems

C++ Solution

bool identicalTrees(BinaryTreeNode<int>* root1, BinaryTreeNode<int>* root2) {

    

    if(root1 == root2){

        return true;

    }

    if(root1!=NULL && root2==NULL){

        return false;

    }

    if(root1==NULL && root2!=NULL){

        return false;

    }

 

    bool left = identicalTrees(root1->left,root2->left);

    bool right = identicalTrees(root1->right,root2->right);

 

    bool check = root1->data==root2->data;

 

    if(left && right && check){

        return true;

    }

    else{

        return false;

    }

}

50 views
0 replies
1 upvote

Interview problems

Crisp C++ solution

bool identicalTrees(BinaryTreeNode<int>* root1, BinaryTreeNode<int>* root2) {   
    if(root1==NULL && root2==NULL){
        return true;
    }
    else if((root1!=NULL && root2==NULL) || (root1==NULL && root2!=NULL)){
        return false;
    }
    else if(root1->data == root2->data){
        bool l = identicalTrees(root1->left, root2->left);
        bool r = identicalTrees(root1->right, root2->right);

        return l && r;

    } 	 
    return false;
    

}
35 views
0 replies
0 upvotes

Interview problems

Simple one line recursive Solution

bool identicalTrees(BinaryTreeNode<int>* r1, BinaryTreeNode<int>* r2) {

    return (!r1 && !r2 || (r1 && r2) && identicalTrees(r1->left,r2->left) && identicalTrees(r1->right,r2->right) );

}

17 views
0 replies
0 upvotes

Interview problems

Most efficient O(n) complexity solution.

bool identicalTrees(BinaryTreeNode<int>* root1, BinaryTreeNode<int>* root2) {

    // Write your code here.     

    if(root1 == NULL || root2 == NULL){

        return (root1 == root2);

    }

    return (root1->data == root2->data)&&identicalTrees(root1->left,root2->left)&&identicalTrees(root1->right,root2->right);

}

20 views
0 replies
0 upvotes

Interview problems

O(n) easy solution in C++ | Striver sheet solution

bool isidentical(BinaryTreeNode<int>* root1, BinaryTreeNode<int>* root2){
    if(root1 == nullptr && root2== nullptr) return true;
    if(root1 == nullptr && root2 != nullptr) return false;
    else  if(root2 == nullptr && root1 != nullptr) return false;
    
    if(root1->data != root2->data) return false;
   
    
   return isidentical(root1->left,root2->left) && isidentical(root1->right,root2->right);
   
    

}

bool identicalTrees(BinaryTreeNode<int>* root1, BinaryTreeNode<int>* root2) {
    bool checkr = true;
    checkr= isidentical(root1, root2);
    return checkr;	 
}

javascript

programming

tutorial

datastructures

+1 more
110 views
0 replies
1 upvote
Full screen
Console