c++ - 如何计算最小公共(public)祖先算法的时间复杂度?

标签 c++ c algorithm time-complexity least-common-ancestor

我进入了一篇讲LCA算法的文章,代码很简单 http://leetcode.com/2011/07/lowest-common-ancestor-of-a-binary-tree-part-i.html

// Return #nodes that matches P or Q in the subtree.
int countMatchesPQ(Node *root, Node *p, Node *q) {
  if (!root) return 0;
  int matches = countMatchesPQ(root->left, p, q) + countMatchesPQ(root->right, p, q);
  if (root == p || root == q)
    return 1 + matches;
  else
    return matches;
}

Node *LCA(Node *root, Node *p, Node *q) {
  if (!root || !p || !q) return NULL;
  if (root == p || root == q) return root;
  int totalMatches = countMatchesPQ(root->left, p, q);
  if (totalMatches == 1)
    return root;
  else if (totalMatches == 2)
    return LCA(root->left, p, q);
  else /* totalMatches == 0 */
    return LCA(root->right, p, q);
}

但是我想知道如何计算算法的时间复杂度,谁能帮帮我?

最佳答案

LCA 的复杂性是 O(h) 其中 h 是树的高度。树高的上限是O(n),其中n表示树中顶点/节点的数量。

如果你的树是平衡的,(参见 AVLred black tree )高度是 log(n) 的顺序,因此算法的总复杂度是 O(log (n))

关于c++ - 如何计算最小公共(public)祖先算法的时间复杂度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24097107/

相关文章:

c++ - 如何计算 Lucas Kanade 流

android - 为什么我们需要使用 android 工具链(或 NDK)来编译在 android 应用程序上下文中运行的 c/c++ 代码?

有人能告诉我这个 C 程序做错了什么吗?

c# - 这是什么算法?

java - java中的交集方法,我如何对交集的边界进行排序,这样我就不会重复

c++ - 根据值实例化不同对象类型的最佳方法?

C++,模板化指向函数的指针

c++ - 如何合并两个不同的 Makefile?

c - C语言struct数组

python - 将两个列表与列表或无值合并的有效方法