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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…