【发布时间】:2015-04-13 18:56:39
【问题描述】:
在another question 中,关于寻找一种算法来计算二叉树的直径,提供了以下代码作为问题的可能答案。
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;
}
在 cmets 部分中,据说上述代码的时间复杂度为 O(n^2)。在给定调用getDiameter 函数时,会为左右子树调用getHeight 和getDiameter 函数。
让我们考虑二叉树的平均情况。高度可以在 Θ(n) 时间计算(对于最坏的情况也是如此)。那么我们如何计算getDiameter函数的时间复杂度呢?
我的两个理论
Τ(n) = 4T(n/2) + Θ(1) = Θ(n^2),考虑高度计算 (相同?)子问题。
T(n) = 2T(n/2) + n + Θ(1) = Θ(nlogn), n = 2*n/2 用于高度计算?
感谢您的时间和精力!
【问题讨论】:
标签: algorithm binary-tree time-complexity