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;
            Queue<TreeNode> q = new LinkedList<>();
            q.add(root.left); q.add(root.right);
                TreeNode L=q.poll();
                TreeNode R=q.poll();
                if(L==null&&R==null) continue;
                else if(L!=null && R!=null &&L.val==R.val){
                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.