Simple Recursive Approach


#1

public class Solution {
public int isSameTree(TreeNode A, TreeNode B) {

    if(A == null && B == null)
        return 1;
    if((A== null && B!= null) || (B == null && A != null))
        return 0;
        
   
   if(A.val == B.val){
       int left = isSameTree(A.left,B.left);
       int right = isSameTree(A.right,B.right);
       if(left == 1 && right == 1)
            return 1;
        return 0;
   }
   
   return 0;
    }

}


#2

More simple recursive approach.

 bool isEqual(TreeNode* root1,TreeNode* root2)
 {
    if(root1==NULL and root2==NULL) return 1;
    if(root1==NULL || root2==NULL) return 0;
    
    if(root1->val==root2->val and isEqual(root1->left,root2->left) and isEqual(root1->right,root2->right))
    {
        return 1;
    }
    
    return 0;
 }
int Solution::isSameTree(TreeNode* A, TreeNode* B) {
    return isEqual(A,B) ? 1 : 0;
}

#4
  //Even simpler recursive approach
     int Solution::isSameTree(TreeNode* A, TreeNode* B) {
       if(A==NULL&&B==NULL){    
            return true;
        }
        if(A==NULL||B==NULL||A->val!=B->val){
            return false;
        }
        return isSameTree(A->left,B->left)&&isSameTree(A->right,B->right);
    }

#5

//Most simpler approach

bool solve(TreeNode* A,TreeNodeB){
if(A==NULL&&B==NULL) return true;
if(A==NULL||B==NULL) return false;
return (A->val==B->val&&solve(A->left,B->left)&&solve(A->right,B->right));
}
int Solution::isSameTree(TreeNode
A, TreeNode* B) {
return solve(A,B);
}