LeetCode in TypeScript

101. Symmetric Tree

Easy

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

Example 1:

Input: root = [1,2,2,3,4,4,3]

Output: true

Example 2:

Input: root = [1,2,2,null,3,null,3]

Output: false

Constraints:

Follow up: Could you solve it both recursively and iteratively?

Solution

import { TreeNode } from '../../com_github_leetcode/treenode'

/*
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */
function isSymmetric(root: TreeNode | null): boolean {
    if (!root.left && !root.right) return true
    const queue: [TreeNode, TreeNode][] = [[root.left, root.right]]
    while (queue.length > 0) {
        let qLen: number = queue.length
        while (qLen-- > 0) {
            const [leftNode, rightNode] = queue.shift()
            if (!leftNode && !rightNode) continue
            if (!leftNode || !rightNode || leftNode.val != rightNode.val) return false
            queue.push([leftNode.left, rightNode.right])
            queue.push([leftNode.right, rightNode.left])
        }
    }
    return true
}

export { isSymmetric }