Using Level Order Traversal


#1

int Solution::isSameTree(TreeNode* A, TreeNode* B) {

//TRIVIAL CASES
if( A == NULL && B == NULL )
    return 1;

if( A == NULL || B == NULL )
    return 0;

//YOU CAN ALSO USE ONE QUEUE
queue <TreeNode *> q1;
queue <TreeNode *> q2;

q1.push( A );
q2.push( B );

while( !q1.empty() && !q2.empty() ){
    
    TreeNode * tr1 = q1.front();
    TreeNode * tr2 = q2.front();
    
    q1.pop();
    q2.pop();
    
    //PUSHING CHILD TO FIRST QUEUE
    if( tr1->left != NULL )
        q1.push( tr1->left );
        
    if( tr1->right != NULL )
        q1.push( tr1->right );
    
    //PUSHING CHILD TO SECOND QUEUE    
    if( tr2->left != NULL )
        q2.push( tr2->left );
        
    if( tr2->right != NULL )
        q2.push( tr2->right );
    
    if( tr1->val != tr2->val )//AT ANY INSTANCE THIS FAILS, SIMPLY SAY FALSE
        return 0;
}

if( q1.empty() && q2.empty() )
    return 1;
    
else
    return 0;

}