對于類,我必須建立一個狀态對象的二叉樹,每個狀态對象都包含一個駐留對象的二叉樹,用于組織生活在每個狀态的人 . 我正試圖在一個特定的州尋找最年長的居民;然而,居民按字母順序排列在樹上,這對我的搜尋完全沒有任何意義 . 是以,我必須周遊整個居民樹,更新儲存最老的人的節點,并在樹完全周遊後傳回它 . 我有我的代碼的第一部分,但我仍然堅持如何編寫其餘的遞歸 .
狀态樹的方法:
node * findoldest (int obd, node * oldest, node * 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 * o_left = findoldest(obd, oldest, n->left);
node * o_right = findoldest(obd, oldest, n->right);
node * 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));
}
}
然後是公共“包裝器”狀态樹方法:
node * findoldest ()
{ int oldest_bday = root->data->birthday;
node * oldest_person = root;
findoldest(oldest_bday, oldest_person, root);
}