Nine-chapter algorithm surface question 56 recent public ancestor

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.