Symmetric Tree

Easy Topics Company Tags

Return true if the binary tree is symmetric about its root, or false otherwise. Mirrored positions must either both be absent or contain equal values: a left child on one side corresponds to a right child on the other.

Examples encode trees in level order. After the root, each present node contributes its left and right child entries in queue order; null marks a missing child, and trailing missing entries may be omitted.

Example 1:

Symmetric Tree, example 1: illustration of the example

Input: root = [9,4,4,null,7,7,null]

Output: true

Explanation: The two children both have value 4. The left child has a right child with value 7, mirrored by the right child's left child with value 7. The outer child positions are both empty.

Example 2:

Symmetric Tree, example 2: illustration of the example

Input: root = [9,4,4,null,7,null,7]

Output: false

Explanation: Both nodes with value 4 have only a right child. These child positions do not mirror one another, even though both grandchildren have value 7, so the tree is not symmetric.

Example 3:

Symmetric Tree, example 3: illustration of the example

Input: root = [0]

Output: true

Explanation: A single root has no children. Its two sides are both empty, so it is symmetric.

Constraints:

  • The tree contains between 1 and 1000 nodes.
  • -100 <= Node.val <= 100

Follow-up: Can you solve the problem both recursively and iteratively?



Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.