How exactly does the below code block work? More specifically, how does the program know which option to return?
return ancestor (node1->left(), node2)
|| ancestor (node1->right(), node2)
|| ancestor (node2->left(), node1)
|| ancestor (node2->left(), node1);
This code block is part of code to traverse a tree in order to determines if one node is an ancestor of the other one when given node1 and node2 in a tree.
Note that node1 and node2 are passed in to the function that is responsible for determining if there is a possible ancestor/descendent relationship:
bool ancestor (const Binary_node<Type> * node1, const Binary_node<Type> * node2)
{
// .... code
}
The program will keep trying the options, until it finds one that works.
In each call to ancestor(), the function will try four possibilities:
If all four possibilities failed, then nodes node1 and node2 are surely not related via ancestor relationship.
Warning: As implemented, the ancestor function is extremely slow, except for very small trees. Because we try four options in each ancestor() call, the number of states roughly quadruples if you increase the height of the tree by 1.