Your question is Check If a Tree Is Balanced. Start with the requirements on the right.
Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.
MSCI analytics services can represent hierarchical structures as binary trees. Given the root of a binary tree, determine whether the tree is height-balanced.
A binary tree is height-balanced when, for every node, the heights of its left and right subtrees differ by no more than 1.
Implement is_balanced(root), where root is either None or a nested dictionary with this structure:
value: an integer node valueleft: another node dictionary or Noneright: another node dictionary or NoneReturn True if the tree is height-balanced, otherwise return False. The values do not affect the result.
Your solution should avoid repeatedly calculating subtree heights. Use a depth-first strategy that detects imbalance while returning height information to each parent.
def is_balanced(root):