DSA · Patterns, not puzzles
How do you calculate tree height and check balance?
Short answer
Height is the number of edges on the longest path from a node to a leaf. A tree is balanced when every node's left and right subtree heights differ by at most one, which can be checked in one postorder pass.
A naive balance check computes the height of every subtree separately, which can become O(n^2) on a skewed tree. The better approach returns both the height and a balance signal from one postorder traversal, so each node is visited once.
function checkBalance(node) {
if (node === null) return 0;
const left = checkBalance(node.left);
if (left === -1) return -1;
const right = checkBalance(node.right);
if (right === -1) return -1;
if (Math.abs(left - right) > 1) return -1;
return Math.max(left, right) + 1;
}
function isBalanced(root) {
return checkBalance(root) !== -1;
}Definitions to keep straight
- Height of a leaf is 0 by the edge-count convention
- Height of an empty tree is often defined as -1 or 0 depending on context
- Depth is measured from the root down to a node
- A balanced tree has height O(log n)
- The check must apply to every node, not just the root
Height is also the space complexity of a recursive traversal, because the call stack follows one root-to-leaf path. That is why a skewed tree can overflow even though the node count is manageable.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why is the naive balance check O(n^2)?
- 2What is the difference between height and depth?
- 3How does the one-pass check achieve O(n)?
- 4How would you compute the diameter of a tree?
Say it in the interview
Height is the longest path from a node down to a leaf, and balance means every node's two subtree heights differ by at most one. Instead of recomputing height at every node, I do one postorder pass that returns the height or a sentinel for unbalanced. That keeps the check O(n) time and O(h) stack space. I state the height convention explicitly to avoid off-by-one confusion.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live DSA mock interview and get scored feedback on depth, clarity and confidence.