A clean self-explanatory iterative solution using Queue


  • 0
    A
    public class Solution {
        public boolean isSymmetric(TreeNode root) {
            Queue<TreeNode> ql = new LinkedList<TreeNode>();
            Queue<TreeNode> qr = new LinkedList<TreeNode>();
            
            if(root == null) return true;
            if(root.left != null)
                ql.offer(root.left);
            if(root.right != null)
                qr.offer(root.right);
            
            while(ql.size() != 0 && qr.size() != 0){
                TreeNode left = ql.poll();
                TreeNode right = qr.poll();
                if(left.val != right.val 
                    || (left.left == null && right.right != null)
                    || (left.left != null && right.right == null)
                    || (left.right == null && right.left != null)
                    || (left.right != null && right.left == null))
                    return false;
                
                if(left.left != null) ql.offer(left.left);
                
                if(left.right != null) ql.offer(left.right);
                
                if(right.right != null) qr.offer(right.right);
                
                if(right.left != null) qr.offer(right.left);
            }
            
            return ql.size() == qr.size();
        }
    }

Log in to reply
 

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