Nine Chapters count judges Net-original website
http://www.jiuzhang.com/problem/56/
Topics
Given a binary tree and two nodes on a two-fork tree, find the nearest common ancestor of these two points (Lowest Common Ancestor, LCA).
As below this binary tree:
1
/ \
2 3
/ \
4 5
The nearest public ancestor of 4 and 5 is the recent public ancestor of 3,2 and 4, which is the recent public ancestor of 3 and 1 (assuming itself to be its own ancestor)
Follow up Question 1: What should the algorithm look like if each node in the tree stores its own parent node?
Follow up Question 2: If each node in the tree does not have its own parent node, but give you the root node of the binary tree, what should the algorithm look like?
Answer
For a two-fork tree with a parent node, the method is simply to list all the points from the two nodes online to the root, and then reverse the position of the first fork.
For a two-fork tree without a parent node, root must be given. Then, starting from root, we use the divide-and-conquer algorithm to find two nodes on each side. If there is an LCA, return to LCA and return to one of the points if one is encountered.
Reference Program
http://www.ninechapter.com/solutions/lowest-common-ancestor/http://www.ninechapter.com/solutions/ lowest-common-ancestor/http://www.ninechapter.com/solutions/lowest-common-ancestor/http://www.ninechapter.com/ solutions/lowest-common-ancestor/
Nine-chapter algorithm surface question 56 recent public ancestor