简体   繁体   English

二叉树的直径-算法复杂度

[英]Diameter of Binary Tree - Algorithm Complexity

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). 在注释部分中,可以说上述代码的时间复杂度为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. 在给定的getDiameter函数调用中, getDiameter左右子树调用getHeightgetDiameter函数。

Let's consider the average case of a binary tree. 让我们考虑二叉树的平均情况。 Height can be computed at Θ(n) time (true for worst case too). 可以在Θ(n)时间计算高度(对于最坏的情况也是如此)。 So how do we compute the time complexity for the getDiameter function? 那么我们如何计算getDiameter函数的时间复杂度呢?

My two theories 我的两个理论

  1. Τ(n) = 4T(n/2) + Θ(1) = Θ(n^2), height computation is considered (same?) subproblem. τ(n)= 4T(n / 2)+Θ(1)=Θ(n ^ 2),高度计算被视为(相同?)子问题。

  2. T(n) = 2T(n/2) + n + Θ(1) = Θ(nlogn), n = 2*n/2 for height computation? T(n)= 2T(n / 2)+ n +Θ(1)=Θ(nlogn),n = 2 * n / 2用于高度计算?

Thank you for your time and effort! 感谢您的时间和精力!

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. 在这种情况下,我们需要从根到叶的n操作来找到高度,从根的子代到叶的n - 1等等。 This gives O(n^2) operations to find the height alone for all nodes. 这使O(n^2)操作可以单独查找所有节点的高度。

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. 然后,我们将花费O(n)时间来查找所有高度。 Then the complexity of finding the diameter would be of the following type: 那么找到直径的复杂度将是以下类型:

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

where a is the size of the left subtree. 其中a是左子树的大小。 This relation would give linear time for finding diameter also. 该关系还将给出寻找直径的线性时间。 So the total time would be linear. 因此,总时间将是线性的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM