Reputation: 89
For class, I have to create a binary tree of state objects, each of which includes a binary tree of resident objects organizing the people who live in each state. I'm trying to search a given state for its oldest resident; however, the residents are organized in the tree by alphabetical order, which does absolutely nothing for my search. Thus, I have to traverse the entire tree of residents, updating the node that saves the oldest person, and return it once the tree has been fully traversed. I have the first part of my code but am stuck on how to write the rest of the recursion.
The state tree's method:
node <Person*> * findoldest (int obd, node <Person*> * oldest, node <Person*> * n)
{
//FINAL WORKING CODE
if (root == NULL)
return NULL;
if (n == NULL)
return NULL;
else
{
if (n->data->birthday < obd)
{
obd = n->data->birthday;
oldest = n;
}
node <Person*> * o_left = findoldest(obd, oldest, n->left);
node <Person*> * o_right = findoldest(obd, oldest, n->right);
node <Person*> * res;
if (o_right && o_left)
if (o_right->data->birthday < o_left->data->birthday)
res = o_right;
else
res = o_left;
else
res = (o_right != NULL ? o_right : o_left);
if (res && oldest)
if (res->data->birthday < oldest->data->birthday)
return res;
else
return oldest;
else
return ((res != NULL ? res : oldest));
}
}
And then the public "wrapper" state tree method:
node <Person*> * findoldest ()
{ int oldest_bday = root->data->birthday;
node <Person*> * oldest_person = root;
findoldest(oldest_bday, oldest_person, root);
}
Upvotes: 0
Views: 868
Reputation: 198
This the pseudo-code you need:
node <Person*> * findoldest (node <Person*> * n)
{
if n->right != null :
right_oldest = findoldest(n->right)
if n->left != null:
left_oldest = findoldest(n->left)
return the node that has max value in (right_oldest.data.birthday, left_oldest.data.birthday, n.data.birthday)
}
Upvotes: 2
Reputation: 394
Essentially, it's the same answer as your last post.
right_old = findoldestn(n->right);
left_old = findoldestn(n->left);
then figure out the oldest one between left/right and current, and return that value. And that can be put in place with
res = (right_old->age > left_old->age ? right_old : left_old);
finalRet = (res->age > oldest->age ? res : oldest);
return (finalRet);
Or an equivalent with if notation :
if (right_old->age >left_old->age)
res = right_old;
else
res = left_old;
if (res->age > oldest->age)
finalRes = res;
else
finalRes = oldest;
Fyi, i'm lazy, variable->age is equivalent to variable->data->birthday.
Upvotes: 1