Problem description:

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

Example 1:

https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg

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

Example 2:

https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg

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

Constraints:

  • The number of nodes in the tree is in the range [1, 1000].
  • 100 <= Node.val <= 100

Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
# subfunction to check if two side are equal
if not root:
return True
def check(left, right):
if not left and not right:
return True
if not left or not right:
return False
if left.val != right.val:
return False
return check(left.right, right.left) and check(left.left, right.right)
return check(root.left, root.right)

time complexity: $O()$
space complexity: $O()$
reference:
related problem: