需要编写一个C++函数来搜索二叉树中的特定元素

问题描述 投票:0回答:1

需要编写一个C++函数,在二叉树中查找用户指定的zodiac_sign字段值的元素,如果没有这样的元素,则打印相应的消息。

我写了以下代码:

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);
}

我有一个问题,我收到几条消息,即使找到该元素,该元素也不存在。我猜这是因为递归,但我不明白如何解决它。

c++ recursion binary-tree
1个回答
1
投票

快速重构代码。进行独立于结果打印的递归搜索,否则尝试确定何时显示“未找到”消息会变得很棘手。

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;
}

tree* 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]);
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.