Compact Iterative Solution in Java


  • 1
    G
    public boolean isSymmetric(TreeNode root) {
           if(root==null){
               return true;
           }
           Queue<TreeNode> queue = new LinkedList();
           queue.offer(root.left);
           queue.offer(root.right);
           while(!queue.isEmpty()){
               TreeNode t1 = queue.poll();
               TreeNode t2 = queue.poll();
               if(t1==null && t2==null){
                   continue;
               }
               else if(t1==null || t2==null){
                   return false;
               }
               if(t1.val!=t2.val){
                   return false;
               }
               queue.offer(t1.left);
               queue.offer(t2.right);
               queue.offer(t1.right);
               queue.offer(t2.left);
           }
           return true;
        }
    

Log in to reply
 

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