简体   繁体   中英

Lowest Common Ancestor (LCM) involving root node

Assuming I have the below binary search tree,

       30
       /\
      /  \
     8   52
    /\
   /  \
  3   20
      /\
     /  \
    10  29

What is the LCM of the following:

  • 30 and 8
  • 20 and 29

I don't want code but I want to know so that I can think of how to come up with my own way of solving the problem.

This becomes pretty easy since this is a search tree, but at your request I won't provide too many details.

1) Look at your root. If it's one of the two numbers, you've found your common ancestor.

2) Else, given that this is a search tree, you can quickly determine which subtree(s) they will appear. Consider what you then must do (a) if they are in the left subtree, (b) if they are in the right subtree, or (c) one is in the left and one is in the right.

Good luck!

The lowest common ancestor (LCA) of two nodes v and w in a tree is the lowest (ie deepest) node that has both v and w as descendants, where we define each node to be a descendant of itself (so if v has a direct connection from w, w is the lowest common ancestor).

So here 30 is the LCM of 30 and 8. And 20 is the LCM of 20 and 29. LCM of 20 and 52 is 30 since it is the lowest node that has both 20 and 52 as descendants.

The lowest common ancestor can be defined as the only node in the tree that satisfies two conditions:

A. all target nodes are either this node or a decendent of this node and B. no children of this node satisfy condition A

So you are looking for a node where condition A is true for the node but none of its children. We know the root node satisfies condition A (by definition). So the algorithm looks like the following, starting at root:

  1. if this node is in the target list then it is the LCA
  2. otherwise search children for nodes satisfying condition A
  3. for any satisfying, start again at step 1 for that child
  4. if none satisfy then you have your lowest common ancestor

This algorithm will work for any number of targets not just 2 as in your question.

I know you didn't want code but I encourage you to look at using Java 8 streams for this: they are quite elegant for this type of situation in which you are iterating through children looking for conditions to be met.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM