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.
# class TreeNode
#     attr_accessor :val, :left, :right
#     def initialize(val = 0, left = nil, right = nil)
#         @val = val
#         @left = left
#         @right = right
#     end
# end
# @param {TreeNode} root
# @return {Boolean}
def is_symmetric(root)
  return true if root.nil?

  helper_symmetric(root.left, root.right)
end

private

def helper_symmetric(left_node, right_node)
  return left_node.nil? && right_node.nil? if left_node.nil? || right_node.nil?

  return false if left_node.val != right_node.val

  helper_symmetric(left_node.left, right_node.right) && helper_symmetric(left_node.right, right_node.left)
end