Height Called Everywhere
A common way to write the balance check:
int height(Node u) {
if (u == null) return -1;
return 1 + Math.max(height(u.left), height(u.right));
}
boolean isBalanced(Node u) {
if (u == null) return true;
return Math.abs(height(u.left) - height(u.right)) <= 1
&& isBalanced(u.left) && isBalanced(u.right);
}
Run isBalanced on a perfect binary tree of 31 nodes, so no short circuit ever fires. Count only the non-null nodes that height walks into, summed over every call isBalanced makes.
How many node visits is that?
Sign in to answer questions and track your progress
Sign In