101. Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

Follow up: Solve it both recursively and iteratively.

# 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 isSymmetric(root,root)
end

def isSymmetric(r1, r2)
  return true if r1.nil? && r2.nil?
  return false if r1.nil? || r2.nil?
  return (r1.val == r2.val) && (isSymmetric(r1.right, r2.left)) && (isSymmetric(r1.left, r2.right))
end

Last updated

Was this helpful?