/* Function to get diameter of a binary tree */
int diameter(struct node * tree)
{
/* base case where tree is empty */
if (tree == 0)
return 0;
/* get the height of left and right sub-trees */
int lheight = height(tree->left);
int rheight = height(tree->right);
/* get the diameter of left and right sub-trees */
int ldiameter = diameter(tree->left);
int rdiameter = diameter(tree->right);
return max(lheight + rheight + 1, max(ldiameter, rdiameter));
}
int height(struct node* node)
{
/* base case tree is empty */
if(node == NULL)
return 0;
/* If tree is not empty then height = 1 + max of left
height and right heights */
return 1 + max(height(node->left), height(node->right));
}
如何用此實現查找樹的直徑的時間複雜度是O(n^2),其中n是樹中節點的數量?獲取以下遞歸實現的時間複雜度
只是一個想法。我們不能記憶高度,我們是否應該每次計算? – thefourtheye
我知道這個實施不是最佳的,我知道另一個O(n)的時間算法,但我需要了解這個實現的時間複雜度是如何爲O(n^2)? –
O(N)?那是什麼?我知道一個算法是從根進行DFS並找到最遠的節點(FN1)。然後做DFS從FN1中找出最遠的節點,它會給出直徑。 – thefourtheye