c++ - How to compute a least common ancestor algorithm's time complexity? -


i came article talking lca algorithms, code simple http://leetcode.com/2011/07/lowest-common-ancestor-of-a-binary-tree-part-i.html

// return #nodes matches p or q in 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 wondering how compute time complexity of algorithm,can me?

the worst case algorithm if nodes sibling leave nodes.

node *lca(node *root, node *p, node *q) {   root call countmatchespq;   for(root->left_or_right_child) call countmatchespq; /* recursive call */   for(root->left_or_right_child->left_or_right_child) call countmatchespq;   ...   for(parent of leave nodes of p , q) call countmatchespq; } 

countmatchespq called height of tree times - 1. lets call height of tree h.

now check complexity of helper function

int countmatchespq(node *root, node *p, node *q) {   search p , q in left sub tree recursively   search p , q in right sub tree recursively } 

so extensive search , final complexity n n number of nodes in tree.

adding both observations, total complexity of algorithm is

o(h * n) 

if tree balanced, h = log n (rb tree, treap etc) if tree unbalanced, in worse case h may n

so complexity in terms of n can given as

for balanced binary tree: o(n logn)
to more precise, actual h(n + n/2 + n/4...) for balanced tree , hence should come 2hn
for unbalanced binary tree: o(n2)
to more precise, actual h(n + n-1 + n-2...) for balanced tree , hence should come h x n x (n+1) / 2

so worse case complexity n2

your algorithm doesn't use memory. using memory save path, can improve algorithm drastically.


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -