I came into an article which talking about the LCA algorithms, the code is simple 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);
}
but I was wondering how compute the time complexity of the algorithm,can anyone help me?
The worst case for this algorithm would be if the nodes are sibling leave nodes.
countMatchesPQ
is called forheight of tree times - 1
. Lets call height of tree ash
.Now check the complexity of helper function
So this is an extensive search and the final complexity is
N
whereN
is the number of nodes in the tree.Adding both observations, total complexity of the algorithm is
If tree is balanced,
h = log N
(RB tree, treap etc) If tree is unbalanced, in worse caseh may be up to N
So complexity in terms of
N
can be given asSo the worse case complexity is N2
Your algorithm doesn't use any memory. By using some memory to save path, you can improve your algorithm drastically.