My queue bsf solution


  • 0
    C
    import java.util.*;
    public class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null && q == null)
            return true;
        if((p == null && q != null) || (p != null && q == null))
            return false;
        
        Queue<TreeNode> q1 = new LinkedList<TreeNode>();
        Queue<TreeNode> q2 = new LinkedList<TreeNode>();
        
        q1.add(p);
        q2.add(q);
        
        while(q1.isEmpty()==false && q2.isEmpty()==false){
            
            TreeNode t1 = (TreeNode)q1.remove();
            TreeNode t2 = (TreeNode)q2.remove();
            
            if(t1.val != t2.val)
                return false;
            if(t1.left != null && t2.left != null){
                q1.add(t1.left);
                q2.add(t2.left);
            }
            if(t1.right != null && t2.right != null){
                q1.add(t1.right);
                q2.add(t2.right);
            }
            if((t1.right != null && t2.right == null) || (t1.right == null && t2.right != null) || (t1.left != null && t2.left == null) || (t1.left == null && t2.left != null))
                return false;
        }
        return true;
    }
    

    }


Log in to reply
 

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