BFS solution


  • 0
    A
       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<>();
            Queue<TreeNode> q2 = new LinkedList<>();
            q1.add(p);q2.add(q);
            
            while(!q1.isEmpty()){
                p = q1.remove();
                q = q2.remove();
                //checking nodes values
                if(p.val != q.val)
                    return false;
                    
                if(p.left != null)
                    q1.add(p.left);
                    
                if(q.left != null)
                    q2.add(q.left);
                    
                if(q1.size() != q2.size())
                    return false;
                    
                if(p.right != null)
                    q1.add(p.right);
                    
                if(q.right != null)
                    q2.add(q.right);
                    
                if(q1.size() != q2.size())
                    return false;
            }
            return true;
        }
    
    

Log in to reply
 

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