Ruby Solution


  • 0
    M

    Kind of ugly but works.

    def is_balanced(root)
        return true if root.nil?
        is_balanced_node(root)[:balanced?]
    end
    
    def is_balanced_node(node)
        return { balanced?: true, depth: -1 } unless node
        
        left  = is_balanced_node(node.left)
        right = is_balanced_node(node.right)
        
        if left[:balanced?] && right[:balanced?] && (left[:depth] - right[:depth]).abs <= 1
            depth = [left[:depth], right[:depth]].max + 1
            return { balanced?: true,  depth: depth }
        else
            return { balanced?: false, depth: 0 }
        end
    end
    

Log in to reply
 

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