Skip to content

Instantly share code, notes, and snippets.

@evidanary
Created June 16, 2017 04:38
Show Gist options
  • Save evidanary/9509310521fad54f3b8a4c445f2e8165 to your computer and use it in GitHub Desktop.
Save evidanary/9509310521fad54f3b8a4c445f2e8165 to your computer and use it in GitHub Desktop.
# 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