2

I am a little confused of the time complexity of the code below:

public int getHeight(TreeNode root) {
    if (root == null) return 0;
    return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
}
public 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);
    }
}

I calculate the time as: T(n) = 2 * T(n / 2) + n, which gives me O(n * log(n)). But in the book, it says the time complexity is O(n ^ 2). Can anyone tell where my calculation is wrong? Thanks!

0

1 Answer 1

1

Your recurrence assumes that the tree is balanced, which would make isBalanced O(n lg n). It appears the book does not make that assumption, so isBalanced becomes O(n2). In the worst case, each internal node could have only one child (such a tree is sometimes called a vine, since it doesn't really branch at all).

For example, here is a worst-case input:

    1
     \
      \
       2
      /
     /
    3
   /
  /
 4
  \
   \
    5
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I think I got your idea. But then is there a way to calculate the complexity using a recurrence formula? It seems that by looking at the code, it is straightforward to get T(n) = 2 * T(n / 2) + n, which is wrong in this case.
I think the closest recurrence that would apply is T(n) = T(n-1) + T(1) + n. It captures the worst case behavior correctly, at the expense of ignoring the expected case. T(n/2) again assumes that each recursive call actually works on (roughly) half the data, which is not true of the worst case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.