3ms Java solution, using level-order traversal with a queue


  • 1
    Y
    public class Solution {
        public boolean isSymmetric(TreeNode root) {
            // 11:25pm
            if (root == null) {
                return true;
            }
            LinkedList<TreeNode> q = new LinkedList<TreeNode>();
            q.offer(root);
            while (!q.isEmpty()) {
                int size = q.size();
                List<Integer> l = new ArrayList<Integer>();
                for (int i=0; i<size; i++) {
                    TreeNode curr = q.poll();
                    if (curr == null) {
                        l.add(null);
                    } else {
                        l.add(curr.val);
                        q.offer(curr.left);
                        q.offer(curr.right);
                    }
                }
                if (!isSymmetricList(l)) {
                    return false;
                }
            }
            return true;
        }
        
        private boolean isSymmetricList(List<Integer> list) {
            int left = 0;
            int right = list.size() - 1;
            while (left <= right) {
                if (list.get(left) != list.get(right)) {
                    return false;
                }
                left++;
                right--;
            }
            return true;
        }
    }

Log in to reply
 

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