1

In another question about finding an algorithm to compute the diameter of a binary tree the following code is provided as a possible answer to the problem.

public static int getDiameter(BinaryTreeNode root) {        
    if (root == null)
        return 0;

    int rootDiameter = getHeight(root.getLeft()) + getHeight(root.getRight()) + 1;
    int leftDiameter = getDiameter(root.getLeft());
    int rightDiameter = getDiameter(root.getRight());

    return Math.max(rootDiameter, Math.max(leftDiameter, rightDiameter));
}

public static int getHeight(BinaryTreeNode root) {
    if (root == null)
        return 0;

    return Math.max(getHeight(root.getLeft()), getHeight(root.getRight())) + 1;
}

In the comments section it's being said that the time complexity of the above code is O(n^2). At a given call of the getDiameter function, the getHeight and the getDiameter functions are called for the left and right subtrees.

Let's consider the average case of a binary tree. Height can be computed at Θ(n) time (true for worst case too). So how do we compute the time complexity for the getDiameter function?

My two theories

  1. Τ(n) = 4T(n/2) + Θ(1) = Θ(n^2), height computation is considered (same?) subproblem.

  2. T(n) = 2T(n/2) + n + Θ(1) = Θ(nlogn), n = 2*n/2 for height computation?

Thank you for your time and effort!

Community
  • 1
  • 1
KostasT
  • 113
  • 7

1 Answers1

2

One point of confusion is that you think the binary tree is balanced. Actually, it can be a line. In this case, we need n operations from the root to the leaf to find the height, n - 1 from the root's child to the leaf and so on. This gives O(n^2) operations to find the height alone for all nodes.

The algorithm could be optimised if the height of each node was calculated independently, before finding the diameter. Then we would spend O(n) time for finding all heights. Then the complexity of finding the diameter would be of the following type:

T(n) = T(a) + T(n - 1 - a) + 1

where a is the size of the left subtree. This relation would give linear time for finding diameter also. So the total time would be linear.

JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57
  • You are right about the worst case scenario and i get the other formula, thanks! We can also compute the height in the same time that we compute the diameter and so achieve O(n). However, if we have a (nearly) balanced tree and we use the above code what formula describes the time complexity correctly? Is my second guess right (to compute the height (logn) of each node (n) we need nlogn operations + O(n) operations for the computation of the diameters)? – KostasT Apr 13 '15 at 21:13
  • Second guess I believe πατριωτακι – JuniorCompressor Apr 13 '15 at 21:14
  • Ok, ευχαριστώ ;) I won't accept the answer yet just in case anyone else wants to help. – KostasT Apr 13 '15 at 21:25