Algorithm 获得低于递归实现的时间复杂度

Algorithm 获得低于递归实现的时间复杂度,algorithm,tree,complexity-theory,Algorithm,Tree,Complexity Theory,使用此实现查找树直径的时间复杂度如何在^2上,其中n是树中的节点数???它在^2上,因为高度计算也是递归的。 您可以编写一个递归关系并求解它 否则 你可以看到fn是线性的,因此c=1 因此,当a是4,递归使用4次,b是树的一半的2时,复杂度是log a到b,让D表示直径,H表示高度。为了方便起见,让我们假设二叉树是完全二叉树,这样左子树和右子树的元素数相等。我们还假设二叉树中有N个元素。现在,直径函数的时间复杂度可以用以下递推关系表示 /* Function to get diameter of

使用此实现查找树直径的时间复杂度如何在^2上,其中n是树中的节点数???

它在^2上,因为高度计算也是递归的。 您可以编写一个递归关系并求解它

否则

你可以看到fn是线性的,因此c=1 因此,当a是4,递归使用4次,b是树的一半的2时,复杂度是log a到b,让D表示直径,H表示高度。为了方便起见,让我们假设二叉树是完全二叉树,这样左子树和右子树的元素数相等。我们还假设二叉树中有N个元素。现在,直径函数的时间复杂度可以用以下递推关系表示

/* 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));
} 
由于以下直径中的递归调用

现在让我们分析一下高度

表示高度时间复杂性的递推关系为

由于高度中的以下递归调用

现在HN=在logN上,通过在2上应用主定理

用1代替这个,我们得到

return 1 + max(height(node->left), height(node->right));
用主定理解3,我们得到logN上的DN=


因此递归函数diameter的复杂性在logN上

只是一个想法。我们不能记住高度,我们应该每次计算吗?我知道这个实现不是最优的,我知道另一个准时算法,但我需要了解这个实现的时间复杂度是如何在^2?On上的?那是哪一个?我知道一种算法,从根开始计算DFS,然后找到最远的节点FN1。然后执行DFS以查找距离FN1最远的节点,该节点将给出直径。通过在同一递归中计算高度,而不是单独调用高度,可以将上述实现优化为On。
  int lheight = height(tree->left);
  int rheight = height(tree->right);

  int ldiameter = diameter(tree->left);
  int rdiameter = diameter(tree->right);
H(N) = 2H(N/2) + c2  ------ 2
return 1 + max(height(node->left), height(node->right));
D(N) = 2D(N/2) + c3 N logN + c1   ------ 3