Wednesday, December 31, 2014

Algorithm to find the first common ancestor of two nodes in a binary tree.

Q. Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a BST.

Algorithm

1. With link to parent node -

Start with any of the two nodes (lets say p). Travel up look at all the nodes in the other branch of the node if there is any. If you find the second node q, then the current node whose left or right child was being searched is the common ancestor.

If, however, you don't find the other node, start with the second node q and repeat the same procedure. If you find p travelling up (since if p did not find q on it's way up, it must be beneath it), then p's parent is the common ancestor (or p if you define a common ancestor that way). If p isn't found, and q reaches the tree's root, p isn't there in the tree.

Whether a node is in the tree or not can be tested by travelling up until you find the root node matching with the root node of the tree you have.

2. Without link to parent node -

Check if left or right of root has p/q.
If p is found and q isn't return p and the opposite for the other case.
If p is found in left and q in right or the opposite case, then current node is the common ancestor.
If p and q are found on the same side, repeat the procedure for that the current node's child which is there at that side (left or right).