Java iterative solution, using Queue


  • 0

    In each loop, take two elements from queue and compare their value, and then add their left and right nodes into queue. Note that the sequence is important.

    public boolean isSymmetric(TreeNode root) {
            if(root==null) return true;
            //iterative
            Queue<TreeNode> q = new LinkedList<>();
            q.add(root.left); q.add(root.right);
            while(!q.isEmpty()){
                TreeNode L=q.poll();
                TreeNode R=q.poll();
                if(L==null&&R==null) continue;
                else if(L!=null && R!=null &&L.val==R.val){
                    q.add(L.left);q.add(R.right);
                    q.add(L.right);q.add(R.left);
                }
                else return false;
            }
            return true;
        }
    

Log in to reply
 

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