Last active
January 16, 2018 08:20
-
-
Save alexspark/73948613378950796e281d0bdd6c416b to your computer and use it in GitHub Desktop.
Check if a binary tree is balanced or not.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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