简体   繁体   English

终止C中的递归函数

[英]Terminating a recursive function in C

int postOrder(struct node* root, char organ[], char bt[], int* val){

    if(root != NULL) {
        postOrder(root->left, organ, bt, val);
        postOrder(root->right, organ, bt, val);
        if(strcmp(root->organ.organname, organ) == 0){
            if(strcmp(root->organ.bloodtype, bt) == 0){
               if(val == 0){
                printf("%s\n", root->organ.name);
                val = 1;
                }
            }
        }
    }
}

I'm trying to terminate this recursive function right after the first print. 我正在尝试在第一次打印后立即终止此递归函数。 My idea originally was to pass in a decimal pointer 'val' and set that to 1 when I wanted to terminate the function. 我最初的想法是传递一个十进制指针“ val”,并在我想终止该函数时将其设置为1。 The thought process is it would change the value outside of the function so all of the previous calls would have the updated pointer, but I don't think that's how it works in this setup. 考虑的过程是它将更改函数外部的值,因此所有先前的调用都将具有更新的指针,但是我认为这不是此设置中的工作方式。

This function searches post the Post Orderly through a binary tree. 此功能通过二叉树搜索Post Postly。

Use *val . 使用*val val is just a pointer. val只是一个指针。 You want the value of it. 您想要它的价值。

Since currently your function does not return anything, you can change it to return 1 if it has printed anything, and return 0 if it does not. 由于当前您的函数不返回任何内容,因此可以将其更改为:如果已打印任何内容,则返回1否则,则返回0 This way you wouldn't need to pass val pointer (which you are not using correctly anyway). 这样,您将不需要传递val指针(无论如何您都没有正确使用它)。

int postOrder(struct node* root, char organ[], char bt[]){
    if(root == NULL)  return 0;
    if (postOrder(root->left, organ, bt, val)) return 1;
    if (postOrder(root->right, organ, bt, val)) return 1;
    if (strcmp(root->organ.organname, organ) == 0 && strcmp(root->organ.bloodtype, bt) == 0) {
        printf("%s\n", root->organ.name);
        return 1;
    }
    return 0;
}

val is a pointer to an integer so you will need to dereference it when setting or getting its value. val是指向整数的指针,因此在设置或获取其值时需要取消引用它。

Try: 尝试:

if(*val == 0) { *val = 1; ... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM