> Uploading knowledge... _
[░░░░░░░░░░░░░░░░░░░░░░░░] 0%
blog logo
> CHICIO CODING_Pixels. Code. Unplugged.

Symmetric Tree

Leetcode Problem 101: Symmetric Tree

Problem Summary

Given the root of a binary tree, determine whether the tree is symmetric (a mirror image of itself around its center). A tree is symmetric if, at every level, the left subtree is a mirror reflection of the right subtree.

Constraints:

  • The tree has between 1 and 1,000 nodes.
  • Node values are integers in the range [-100, 100].

Techniques

  • Tree
  • Depth-First Search
  • Breadth-First Search
  • Binary Tree

Solution

export 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 isSymmetricRecursive(p: TreeNode | null, q: TreeNode | null): boolean {
    if (!p && !q) {
        return true
    }

    if (!p || !q) {
        return false
    }

    return p.val === q.val && isSymmetricRecursive(p.left, q.right) && isSymmetricRecursive(p.right, q.left)
}


function isSymmetric(root: TreeNode | null): boolean {
    if (!root) {
        return true
    }

    return isSymmetricRecursive(root.left, root.right)
}