1ms Java Solution using recursion with Explanation


  • 0
    G

    I have first checked the base condition in which both trees are null
    Then I checked condition 1 in which 1 is null and other is not last condition is 1 is not null and 2 is null
    In all above cases result will be false because of assymetry

    Last condition is nothing, but calling recursion on left nodes of both trees and right nodes of both trees and anding it with condition that value of root node of both trees is equal (because if it is not then even of childs are equal trees are not)

    ...

    public boolean isSameTree(TreeNode p, TreeNode q) {
    if(p==null && q==null) {
    return true;
    }

        if(p==null && q!=null) {
            return false;
            
        }
    
        if(p!=null && q==null) {
            return false;
            
        }
        
    
        
       boolean retValue = isSameTree(p.left,q.left) && isSameTree(p.right,q.right) && p.val==q.val;
       return retValue;
        
    }
    

    ...


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.