algorithm - 获取以下递归实现的时间复杂度

标签 algorithm tree complexity-theory

/* 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 是树中的节点数??

最佳答案

是O(n^2) 因为高度计算也是递归的。 你可以写一个递归关系并解决它。

否则 Master's theorem

您可以看到 f(n) 是线性的,因此 c = 1 所以当 a 为 4(递归使用 4 次)且 b 为 2(在树的一半上)时,复杂度为 a 到 b 的对数

关于algorithm - 获取以下递归实现的时间复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17183249/

相关文章:

algorithm - 给定两个点集 A 和 B,如何找到 A 中离 B 最远的点?

algorithm - 图中的每条桥都是 DFS 搜索树中的一条边吗?

algorithm - 返回所有小于 M 的素数

javascript - 将 JSON 树结构读取到自定义 javascript 对象中

performance - 证明平衡二叉搜索树的高度为log(n)

algorithm - 复杂性理论-排序算法

java - 时间序列数据 - 计算两组的出现次数

java - 使用 Stack 跟踪一般树中节点的所有祖先

algorithm - 从二进制最大堆中删除第二个最小的元素

algorithm - "house coloring with three colors"是NP吗?