Skip to content

Instantly share code, notes, and snippets.

@alexspark
Last active January 16, 2018 08:20
Show Gist options
  • Save alexspark/73948613378950796e281d0bdd6c416b to your computer and use it in GitHub Desktop.
Save alexspark/73948613378950796e281d0bdd6c416b to your computer and use it in GitHub Desktop.
Check if a binary tree is balanced or not.
class Node
attr_accessor :value, :left, :right
def initialize(value)
@value = value
end
end
def is_height_balanced?(node)
return true if node.nil?
return (
(height(node.left)-height(node.right)).abs <= 1) &&
is_height_balanced?(node.left) &&
is_height_balanced?(node.right)
)
end
def height(node)
return 0 if node.nil?
return 1 + [height(node.left), height(node.right)].max
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment