Skip to content

Instantly share code, notes, and snippets.

@mooreniemi
Created September 8, 2016 14:46
Show Gist options
  • Save mooreniemi/3e4035a55d8b8f349463aa0cf2b3d761 to your computer and use it in GitHub Desktop.
Save mooreniemi/3e4035a55d8b8f349463aa0cf2b3d761 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)
# @val = val
# @left, @right = nil, nil
# end
# end
# @param {TreeNode} root
# @return {Boolean}
def is_balanced(root)
bool, _ = is_balanced?(root)
bool
end
def is_balanced?(root)
return [true, 0] if root.nil?
return [true, 1] if root.left.nil? && root.right.nil?
#1) Left subtree of T is balanced
l, l_depth = is_balanced?(root.left)
#2) Right subtree of T is balanced
r, r_depth = is_balanced?(root.right)
#3) The difference between heights of left subtree and right subtree is not more than 1.
# abs prevents errors from left side being smaller
[r && l && ((l_depth - r_depth).abs <= 1), [l_depth, r_depth].max + 1]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment