Solution using Breadth First Search


  • 0
    O
    
        public boolean isSymmetric(TreeNode root) {
            if(root == null) {
                return true;
            }
            int size = 0, head = 0, tail = 0;
            List<TreeNode>  q = new ArrayList<TreeNode>();
            TreeNode tmp, tmpHead;
            q.add(root);
            List<TreeNode> list = new ArrayList<TreeNode>();
            while(!q.isEmpty()) {
                size = q.size();
                list.clear();
                while(size > 0) {
                    tmp = q.remove(0);
                    if (tmp.left != null) {
                        q.add(tmp.left);
                    }
                    if (tmp.right != null) {
                        q.add(tmp.right);
                    }
                    list.add(tmp.left);
                    list.add(tmp.right);
                    size--;
                }
                tail = list.size() - 1;
                for(head = 0; head < tail; head++, tail--) {
                    tmpHead = list.get(head);
                    tmp = list.get(tail);
                    if((tmp == null && tmpHead != null) || (tmp != null && tmpHead == null)) {
                        return false;
                    } else if(tmp != null && tmpHead != null && tmp.val != tmpHead.val) {
                        return false;
                    }
                }
            }
            
            return true;
        }
    

Log in to reply
 

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