My queue bsf solution


  • 0
    C
    import java.util.*;
    public class Solution {
    public boolean isSymmetric(TreeNode root) {
        
        Queue <TreeNode> q1 = new LinkedList<TreeNode> ();
        Queue <TreeNode> q2 = new LinkedList<TreeNode> ();
        
        if(root == null || ((root.right == null) && (root.left == null)))
            return true;
        
        if(root.left== null || root.right== null)
            return false;
        
        q1.add(root.left);
        q2.add(root.right);
        
        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.right == null) || (t1.left == null && t2.right != null) || (t1.right != null && t2.left == null) || (t1.right == null && t2.left != null))
            return false;
         if(t1.left != null && t2.right != null)
             {q1.add(t1.left);q2.add(t2.right);}
         if(t1.right != null && t2.left != null)
             {q1.add(t1.right);q2.add(t2.left);}
        }
        return true;
    }
    

    }


Log in to reply
 

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