Iterative java solution with explanation


  • 4
    J

    Basically, it is BFS with a queue. I was inspired by another question of serialize/deserialized tree. So I just serialize each level of the tree and check if it is palindrome. if the node is null, just put "X" in the array.

    public boolean isSymmetric(TreeNode root) {
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while(!q.isEmpty()) {
            int size = q.size();
            String[] arr = new String[size];
            for(int i=0;i<size;i++) {
                TreeNode node = q.poll();
                if(node!=null) {
                    arr[i] = node.val+"";
                    q.offer(node.left);
                    q.offer(node.right);
                } else
                    arr[i] = "X";
            }
            int l=0,r=size-1;
            while(l<r)
                if(!arr[l++].equals(arr[r--]))
                    return false;
        }
        return true;
    }

Log in to reply
 

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