Created
June 16, 2017 04:38
-
-
Save evidanary/9509310521fad54f3b8a4c445f2e8165 to your computer and use it in GitHub Desktop.
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
# find if a tree is balanced | |
# i.e. no two nodes are more than 1 level away from root | |
# i.e. maxdepth - mindepth <= 1 | |
def max_depth(root) | |
return 0 if root.nil? | |
return 1 + [max_depth(root.left) , max_depth(root.right)].max | |
end | |
def min_depth(root) | |
return 0 if root.nil? | |
return 1 + [min_depth(root.left), min_depth(root.right)].min | |
end | |
def is_balanced(root) | |
puts max_depth(root) | |
puts min_depth(root) | |
return max_depth(root) - min_depth(root) <= 1 | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment