6ms Solution in Java using Level-order traversal


  • 0
    L
    public boolean isSymmetric(TreeNode root) {
        LinkedList<TreeNode> q = new LinkedList<>();
        q.add(root);
        while (q.size() != 0) {
            LinkedList<TreeNode> children = new LinkedList<>();
            //next level
            for (TreeNode node : q) {
                if (node != null) {
                    children.add(node.left);
                    children.add(node.right);
                }
            }
            //check if symmetric at this level
            while (q.size() > 1) {
                TreeNode head = q.removeFirst();
                TreeNode tail = q.removeLast();
                if (head == null && tail == null) {
                    continue;
                }
                if (tail == null || head == null || head.val != tail.val) {
                    return false;
                }
            }
            q = children;
        }
        return true;
    }

Log in to reply
 

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