Write code to determine if two trees are identical

Steps:
  • If two nodes are null we reached the end for that subtree and we will return true
  • If two nodes are not null we check for data and check recursively their left and right sub trees
  • If one node is null and other is not null then we return false which is the last statement in the function. 
  
Code:

class Node{
    int data;
    Node left, right;
   
    Node(int data){
        this.data = data;
    }
}

public class IdenticalTrees {
     Node tree1, tree2;
    
     boolean isIdentical(Node n1, Node n2){
         if(n1 == null && n2 == null){
             return true;
         }
         if(n1!= null && n2!=null){
             return ( (n1.data == n2.data) && isIdentical(n1.left, n2.left) && isIdentical(n1.right, n2.right));
         }
         return false;
     }
    
     public static void main(String[] args){
         IdenticalTrees trees = new IdenticalTrees();
       
         trees.tree1 = new Node(2);
         trees.tree1.left = new Node(3);
       
         trees.tree2 = new Node(2);
         trees.tree2.left = new Node(3);
       
         System.out.println(trees.isIdentical(trees.tree1, trees.tree2));
       
     }
   
}


Output:

true









Comments

Popular posts from this blog

Rearrange Array in Maximum-Minimum form

Second Largest Element

Check if a number is a power of another number