Recursive and Iterative Ruby Solution


  • 0
    M
    def is_symmetric(root)
        return true if root.nil?
        is_mirror(root.left, root.right)
    end
    
    def is_mirror(a, b)
        return a == b if a.nil? || b.nil?
        return false  if a.val != b.val
        is_mirror(a.left, b.right) && is_mirror(a.right, b.left)
    end
    
    def is_symmetric(root)
        return true if root.nil?
        
        stack = []
        stack << root.left  if root.left
        stack << root.right if root.right
            
        until stack.empty?
            return false unless stack.size.even?
            
            right = stack.pop
            left  = stack.pop
            return false unless right.val == left.val
            
            return false unless left.left.nil? == right.right.nil?
            stack << left.left   if left.left
            stack << right.right if right.right
            
            return false unless left.right.nil? == right.left.nil?
            stack << left.right  if left.right
            stack << right.left  if right.left
        end
        
        true
    end
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.