The code below tests whether a binary tree is balanced. I have been told that its running time is O(n log n).
To my understanding...
getHeight()visits every node once, so it is O(n).isBalanced()callsgetHeight().. then recurse
If isBalanced() is called on all n nodes, and it calls getHeight() which is O(n), why isn't the complexity O(n²)?
int getHeight(TreeNode root) {
if (root == null) return -1;
return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
}
boolean isBalanced(TreeNode root) {
if (root == null) return true;
int heightDiff = getHeight(root.left) - getHeight(root.right);
if (Math.abs(heightDiff) > 1)
return false;
else
return isBalanced(root.left) && isBalanced(root.right);
}