How to break out of recursion? C Programming

时光总嘲笑我的痴心妄想 提交于 2021-01-07 02:55:46

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!