Skip to content

Instantly share code, notes, and snippets.

@bparanj
Created July 27, 2020 20:43
Show Gist options
  • Save bparanj/1e85d740d7d0d9ffb542dea1553fd82a to your computer and use it in GitHub Desktop.
Save bparanj/1e85d740d7d0d9ffb542dea1553fd82a to your computer and use it in GitHub Desktop.
# Definition for a binary tree node.
# class TreeNode
# attr_accessor :val, :left, :right
# def initialize(val = 0, left = nil, right = nil)
# @val = val
# @left = left
# @right = right
# end
# end
# @param {TreeNode} root
# @return {Boolean}
def height(root)
if root.nil?
return 0
end
left_height = height(root.left)
right_height = height(root.right)
return 1 + [left_height, right_height].max
end
def is_balanced(root)
if root.nil?
return true
end
left_height = height(root.left)
right_height = height(root.right)
if (left_height - right_height).abs > 1
return false
else
return is_balanced(root.left) && is_balanced(root.right)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment