Lowest Common Ancestor of a Binary Tree
Given a binary tree, find the lowest common ancestor of two given nodes in the tree.
1 // This function returns pointer to LCA of two given values n1 and n2. 2 // This function assumes that n1 and n2 are present in Binary Tree 3 struct Node *findLCA(struct Node* root, int n1, int n2) 4 { 5 // Base case 6 if (root == NULL) return NULL; 7 8 // If either n1 or n2 matches with root's key, report 9 // the presence by returning root (Note that if a key is 10 // ancestor of other, then the ancestor key becomes LCA 11 if (root->key == n1 || root->key == n2) 12 return root; 13 14 // Look for keys in left and right subtrees 15 Node *left_lca = findLCA(root->left, n1, n2); 16 Node *right_lca = findLCA(root->right, n1, n2); 17 18 // If both of the above calls return Non-NULL, then one key 19 // is present in once subtree and other is present in other, 20 // So this node is the LCA 21 if (left_lca && right_lca) return root; 22 23 // Otherwise check if left subtree or right subtree is LCA 24 return (left_lca != NULL)? left_lca: right_lca; 25 }
http://leetcode.com/2011/07/lowest-common-ancestor-of-a-binary-tree-part-i.html