Search code examples
c++recursionbinary-tree

Need to write a C++ function that searches for a specific element in a binary tree


Need to write a C++ function that searches for elements with the value of the zodiac_sign field specified by the user in the binary tree and if there is no such element, print the corresponding message.

I have written the following code:

void findZodiacSign(tree* top, char zodiac_sign[10]) {
    if (top == nullptr) {
        return;
    }

    int comparisonResult = std::strcmp(top->inf.zodiac_sign, zodiac_sign);

    if (comparisonResult == 0) {
        // Если значения совпадают, выводим информацию об элементе
        printf("| %10d | %7s | %5s | %10s | %d/%d/%d |\n", top->inf.id, top->inf.last_name, top->inf.first_name, top->inf.zodiac_sign, top->inf.date_of_birth[0], top->inf.date_of_birth[1], top->inf.date_of_birth[2]);
    }
    else {
        cout << "This element does not exist" << endl;
    }

    findZodiacSign(top->left, zodiac_sign);
    findZodiacSign(top->right, zodiac_sign);
}

And I have such a problem that I get several messages that such an element does not exist even if the element was found. I guess that this is because of recursion, but I don't understand how to fix it.


Solution

  • A quick refactor of your code. Do the recursive searching independent of the printing of the result, else it gets tricky trying to determine when to show the "not found" message.

    A couple of other recommendations. Pass zodiac_sign as const char*. The char[10] member of the struct will automatically cast to const char* (because all arrays become pointers when passed a parameters). Even better if you can use std::string and pass as const std::string& Also, don't mix cout and printf. I'll leave that as an exercise for you.

    tree* findZodiacSignImpl(tree* top, const char* zodiac_sign) {
    
        if (top == nullptr) {
             return nullptr;
        }
    
        int comparisonResult = std::strcmp(top->inf.zodiac_sign, zodiac_sign);
        if (comparisonResult == 0) {
            return top;
        }
    
        tree* node = findZodiacSignImpl(top->left, zodiac_sign);
        if (node == nullptr) {
            node = findZodiacSignImpl(top->right, zodiac_sign);
        }
        return node;
    }
    
    void findZodiacSign(tree* top, const char* zodiac_sign) {
        tree* node = findZodiacSignImpl(top, zodiac_sign);
        if (node == nullptr) {
            cout << "This element does not exist" << endl;
        } else {
            printf("| %10d | %7s | %5s | %10s | %d/%d/%d |\n", node->inf.id, node->inf.last_name, node->inf.first_name, node->inf.zodiac_sign, node->inf.date_of_birth[0], node->inf.date_of_birth[1],node->inf.date_of_birth[2]);
        }
    
    }