In fact, we can use the back-order traversal of the tree. When you access the requested node A, if the two nodes are not on the same line, they must be on the left and right trees of node A respectively, node A is required to traverse to the first node that meets this condition in the descending order. In addition, special processing must be performed on the two nodes online.
Code :
Static Bool LCA (node * Root, Int Va, Int VB, node *& Result, node * Parrent)
{
// Whether left/right subtree contains one of the two vertices to be judged
Bool Left = False , Right = False ;
If ( ! Result && Root -> Left) left = LCA (Root -> Left, VA, VB, result, root );
If ( ! Result && Root -> Right) Right = LCA (Root -> Right, VA, VB, result, root );
// Whether the current mid node is one of the two vertices to be judged
Bool Mid = False ;
If (Root -> Data = VA | Root -> Data = VB) Mid = True ;
If ( ! Result && Int (Left + Right + Mid) = 2 ) {
If(MID) Result=Parrent;
ElseResult=Root;
}
Return Left | Mid | Right;
}
Node * LCA (node * Root, Int Va, Int VB)
{
If(Root=Null)ReturnNULL;
Node*Result=NULL;
LCA (root, VA, VB, result, null );
ReturnResult;
}