LeetCode-in-All

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

# Definition for a binary tree node.
#
# defmodule TreeNode do
#   @type t :: %__MODULE__{
#           val: integer,
#           left: TreeNode.t() | nil,
#           right: TreeNode.t() | nil
#         }
#   defstruct val: 0, left: nil, right: nil
# end

defmodule Solution do
  @spec is_symmetric(root :: TreeNode.t() | nil) :: boolean
  def is_symmetric(nil), do: true
  def is_symmetric(%TreeNode{left: left, right: right}) do
    helper(left, right)
  end

  defp helper(nil, nil), do: true
  defp helper(nil, _), do: false
  defp helper(_, nil), do: false
  defp helper(%TreeNode{val: val1, left: left1, right: right1}, %TreeNode{val: val2, left: left2, right: right2}) do
    val1 == val2 and helper(left1, right2) and helper(right1, left2)
  end
end