簡體   English   中英

盡管有真實值,C中的函數始終返回0

[英]Function in C always returning 0 despite true value

typedef struct BinaryTreeNode {
int data;
BinaryTreeNode * left;
BinaryTreeNode * right;
} BinaryTreeNode;

int isElementInBinaryTree(BinaryTreeNode *root, int search_item) {
    if(root) {
        if(search_item == root -> data) return 1;
        isElementInBinaryTree(root -> left, search_item);
        isElementInBinaryTree(root -> right, search_item);
    }
}

int main() {
    BinaryTreeNode one = {1, NULL, NULL}; // root of the binary tree
    BinaryTreeNode two = {2, NULL, NULL};
    BinaryTreeNode three = {3, NULL, NULL};
    BinaryTreeNode four = {4, NULL, NULL};
    BinaryTreeNode five = {5, NULL, NULL};
    BinaryTreeNode six = {6, NULL, NULL};
    BinaryTreeNode seven = {7, NULL, NULL};

    one.left = &two;
    one.right = &three;

    two.left = &four;
    two.right = &five;

    three.left = &six;
    three.right = &seven;

    printf("%d ", isElementInBinaryTree(&one, 4));
    printf("\n");

    return 0;
}

我正在編寫一個名為isElementInBinaryTree的函數,該函數返回1(true)是元素存在,否則返回0。 我不明白為什么盡管二進制樹中存在數字4,但函數總是返回0?

您的代碼在遞歸時實際上不返回任何內容,因此,“返回值”通常是用於該目的的寄存器中剩余的值。

這段代碼

if(root) {
        if(search_item == root -> data) return 1;
        isElementInBinaryTree(root -> left, search_item);
        isElementInBinaryTree(root -> right, search_item);
    }

需要看起來像這樣

if(root) 
{
    if(search_item == root -> data) return 1;

    if (isElementInBinaryTree(root -> left, search_item)) return 1;
    return isElementInBinaryTree(root -> right, search_item);
}
return 0;

最終return 0; 確保在提供NULL指針時返回有意義的內容。

編譯代碼時,它應該顯示有關類型化函數終止而沒有return語句的警告。 您需要注意這些警告並予以解決。

實際上,整個過程可以簡化為一行代碼(盡管不太清楚)

return root && ((search_item == root->data) ||
                isElementInBinaryTree(root->left, search_item) ||
                isElementInBinaryTree(root->right, search_item));

它依賴於快捷方式評估,僅在需要時才執行。

執行遞歸調用時,您不會返回任何內容。 因此,如果在樹的根目錄中找到該項目,它將僅返回1

另外,到達樹的底部時如果找不到任何內容,您將不會返回任何東西,這需要返回0表示失敗。

int isElementInBinaryTree(BinaryTreeNode *root, int search_item) {
    if(root) {
        if(search_item == root -> data) {
            return 1;
        }
        return isElementInBinaryTree(root -> left, search_item) || 
               isElementInBinaryTree(root -> right, search_item);
    } else {
        return 0;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM