Thursday 20 September, 2012

Q.1) Find Lowest Common Ancestor(LCA) of 2 nodes in a binary tree.

With top-down approach, this can become complicated and a straight forward solution can be of O(n^2)
But if we follow bottom up approach, we can solve this in O(n) run time complexity.

Node *LCA(Node *root, Node *p, Node *q) {
if (!root) return NULL;
if (root == p || root == q) return root;

Node *L = LCA(root->left, p, q);
Node *R = LCA(root->right, p, q);

if (L && R) return root; // if p and q are on both sides

//Either both are in left or right sub-trees or may not be present in the tree
return L ? L : R;
}

The above solution fails if P or Q is not present in the tree. We can solve it simply by having a wrapper function which first traverse the tree once to see whether those 2 nodes are present in the tree and then only call the above function.

No comments:

Post a Comment