My answer using level order traversal and array list in java


  • 0
    A

    The nodes at each level are stored in a list.Once a level is traversed, we check if the list is a palindrome of numbers or not.

    public boolean isSymmetric(TreeNode root) {
            if(root == null){
                return true;
            }
            List<Integer> levelString = new ArrayList<Integer>();
            Queue<TreeNode> q = new LinkedList<TreeNode>();
            q.add(root);
            q.add(null);
            while(!q.isEmpty()){
                TreeNode temp = q.remove();
                if(temp==null){
                    if(!q.isEmpty()){
                        System.out.println(levelString);
                        int i =0;
                        int j = levelString.size()-1;
                        while(i<=j){
                            if(!levelString.get(i++).equals(levelString.get(j--))){
                                return false;
                            }
                        }
                        q.add(null);
                        levelString = new ArrayList<Integer>();
                    }
                }
                else{
                    if(temp.left!=null){
                        q.add(temp.left);
                        levelString.add(temp.left.val);
                    }
                    else{
                        levelString.add(Integer.MAX_VALUE);
                    }
                    if(temp.right!=null){
                        q.add(temp.right);
                        levelString.add(temp.right.val);
                    }
                    else{
                        levelString.add(Integer.MAX_VALUE);
                    }
                }
            }
            return true;
            
        }

Log in to reply
 

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