问题
I have a trenary tree every node got id and name how can I return true when root->id=id and break the recursion
BOOLEAN isIdUsed(Trin_Ari *root,int idNumber) {
if (root==NULL)
return FALSE;
if (root->id==idNumber)
return TRUE;
isIdUsed(root->left,idNumber);
isIdUsed(root->middle,idNumber);
isIdUsed(root->right,idNumber);
return FALSE;
}
回答1:
You're ignoring the return values from the recursive calls to isIdUsed
. Once you encounter a TRUE
there, you need to propagate it upwards:
BOOLEAN isIdUsed(Trin_Ari *root,int idNumber) {
if (root==NULL)
return FALSE;
if (root->id==idNumber)
return TRUE;
if (isIdUsed(root->left,idNumber))
return TRUE;
if (isIdUsed(root->middle,idNumber))
return TRUE;
if (isIdUsed(root->right,idNumber))
return TRUE;
return FALSE;
}
回答2:
how can i return true when root->id=id and break the recursion
You can break the recursion as you mentioned, just check if the root ID is the idNumber and then return false. You can just return the three checks at the end such as:
BOOLEAN isIdUsed(Trin_Ari *root,int idNumber) {
if (root==NULL)
return FALSE;
if (root->id==idNumber)
return TRUE;
return isIdUsed(root->left,idNumber) || isIdUsed(root->middle,idNumber) || isIdUsed(root->right,idNumber);
}
回答3:
Your function doesn't take the result of the sub recursions into account. You need to get their returned value to decide if you break the recursion.
BOOLEAN isIdUsed(Trin_Ari *root,int idNumber) {
if (root==NULL)
return FALSE;
if (root->id==idNumber)
return TRUE;
if (isIdUsed(root->left,idNumber))
return TRUE;
if (isIdUsed(root->middle,idNumber))
return TRUE;
if (isIdUsed(root->right,idNumber))
return TRUE;
return FALSE;
}
回答4:
You are missing returning the outcome of the recursive calls...
BOOLEAN isIdUsed(Trin_Ari *root,int idNumber) {
if (root==NULL)
return FALSE;
if (root->id==idNumber)
return TRUE;
if (isIdUsed(root->left,idNumber))
return TRUE;
if (isIdUsed(root->middle,idNumber))
return TRUE;
if (isIdUsed(root->right,idNumber))
return TRUE;
return FALSE;
}
来源:https://stackoverflow.com/questions/65534537/how-to-break-out-of-recursion-c-programming