【发布时间】:2014-06-07 12:19:22
【问题描述】:
我看到一篇讲 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);
}
但我想知道如何计算算法的时间复杂度,有人可以帮我吗?
【问题讨论】:
-
fwiw:如果您可以预先计算所有节点(在 O(n) 时间内),也可以在 O(1) 中找到最低共同祖先en.wikipedia.org/wiki/…
标签: c++ c algorithm time-complexity least-common-ancestor