Intermediate · easy · binary-tree, dfs, recursion
Balanced Binary Tree
The challenge
Given a binary tree, decide whether it is height-balanced: at every node, the heights of the left and right subtrees differ by at most 1.
Example
3
/ \
9 20 -> true
/ \
15 7
1
/ \
2 2 -> false (at the root: height 3 on the left, 1 on the right)
/ \
3 3
/ \
4 4Idea: checking every node with its own call to a height function costs O(n^2) in the worst case. Instead, compute the heights bottom-up in a single depth-first pass, and return -1 as soon as some subtree is not balanced; that -1 then travels up to the root with no more work. The tree is balanced if the answer at the root is not -1. Time O(n), and O(h) of stack for a tree of height h.
The solution
# Balanced Binary Tree - ayotl.dev
class T:
def __init__(self, v, l=None, r=None):
self.v, self.l, self.r = v, l, r
def height(t):
# -1 means: not balanced down here
if not t:
return 0
l, r = height(t.l), height(t.r)
if l < 0 or r < 0 or abs(l - r) > 1:
return -1
return 1 + max(l, r)
def balanced(t):
return height(t) >= 0
a = T(3, T(9), T(20, T(15), T(7)))
b = T(1, T(2, T(3, T(4), T(4)), T(3)),
T(2))
print("true" if balanced(a) else "false")
print("true" if balanced(b) else "false")
$ python3 balanced_binary_tree.py
true
false