Least Common Ancestor of any number of nodes in Binary Tree
Given a binary tree (not a binary search tree) and any number of Key Nodes, the task is to find the least common ancestor of all the key Nodes.
Following is the definition of LCA from Wikipedia:
Let T be a rooted tree. The lowest common ancestor between two nodes n1 and n2 is defined as the lowest node in T that has both n1 and n2 as descendants (where we allow a node to be a descendant of itself).
The LCA of any number of nodes in T is the shared common ancestor of the nodes that is located farthest from the root.
Example: In the figure above:
LCA of nodes 12, 14, 15 is node 3 LCA of nodes 3, 14, 15 is node 3 LCA of nodes 6, 7, 15 is node 3 LCA of nodes 5, 13, 14, 15 is node 1 LCA of nodes 6, 12 is node 6
Following is the simple approach for Least Common Ancestor for any number of nodes.
- For every node calculate the matching number of nodes at that node and its sub-tree.
- If root is also a matching node.
matchingNodes = matchingNodes in left sub-tree + matchingNodes in right sub-tree + 1
- If root is not a matching node.
matchingNodes = matchingNodes in left sub-tree + matchingNodes in right-subtree
- If matching Nodes count at any node is equal to number of keys then add that node into the Ancestors list.
- The First node in the Ancestors List is the Least Common Ancestor of all the given keys.
Below is the implementation of above approach.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.