Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

lowest common ancestor - How to find the LCA of all pair of nodes in a binary tree

There are some algorithms to find the LCA of a given pair of nodes. But is there any algorithm to find the LCA of all pair of nodes in a binary tree in asymptotic time of less than O(n^2)?

I'm specifically looking for an algorithm with a time span of O(n log n)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to think about this problem recursively. Consider the root r of a tree. The LCA of the immediate left chil of r and all of the nodes belonging to the subtree rooted at the immediate right children of r. Do similarly for the immediate right child of r and all the nodes belonging to the tree rooted at the immediate left child of r.

So, let's define a function called LCA as follows (in Pseudo code):

LCA(r)
    if r does not have both a right and left child
        return empty list.
    else
        p1 = pairs made up of left child and all the nodes rooted at right child.
        p2 = pairs made up of right child and all the nodes rooted at the left child.
        p3 = LCA(left child of r)
        p4 = LCA(right child of r)
        return p1 + p2 + p3 + p4

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...