Created
July 27, 2020 20:43
-
-
Save bparanj/1e85d740d7d0d9ffb542dea1553fd82a 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
# 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