【问题标题】:How do I get rid of the warning in this simple recursive implementation of BST如何在 BST 的这个简单递归实现中消除警告
【发布时间】:2020-06-07 14:08:53
【问题描述】:

我正在尝试在 C++ 中实现 DS,这是一个带有插入和搜索功能的二叉搜索树类的简单实现。代码编译并根据需要提供输出。
codereview 有人指出,搜索功能给出警告,搜索功能中的代码被破坏。该警告类似于“并非所有控制路径都有返回语句”,但我认为这就是递归函数的样子。警告是一个问题,我该如何摆脱它?另外,密码是怎么破的?谢谢。

#include <stdio.h>
#include <iostream>

class BstNode{
int data;
BstNode* left;
BstNode* right;

public:
BstNode(int data)
{
    this->data = data;
    this->left = NULL;
    this->right = NULL;
}
~BstNode();

void Insert(int data)
{
    if(this->data >= data)
    {
        if (this->left == NULL)
            this->left = new BstNode(data);
        else 
            this->left->Insert(data);
    }
    else
    {
        if (this->right == NULL)
            this->right = new BstNode(data);
        else 
            this->right->Insert(data);
    }
}

bool Search(int data)
{
    if(this->data == data)
        return true;
    else if(this->data >= data)
    {
        if(this->left == NULL)
            return false;
        else
            this->left->Search(data);
    }
    else
    {
        if(this->right == NULL)
            return false;
        else
            this->right->Search(data);
    }

}
};

int main()
{
BstNode* ptr_root = new BstNode(15);
ptr_root->Insert(10);
ptr_root->Insert(16);
int num;
std::cout<<"Enter the number: \n";
std::cin>> num;
if (ptr_root->Search(num))
    std::cout<<"Found\n";
else
    std::cout<<"Not Found\n";

return 0;
}

【问题讨论】:

  • this-&gt;left-&gt;Search(data); -> return this-&gt;left-&gt;Search(data);。 return 仅终止 current 函数调用。如果一个函数被递归调用,它仍然一次只终止一个调用。
  • 知道了,谢谢HolyBlackCat。

标签: c++ class recursion binary-search-tree function-definition


【解决方案1】:

此函数 Search 在这些路径中不返回任何内容

    else
        this->left->Search(data);

和

    else
        this->right->Search(data);

你必须写

    else
        return this->left->Search(data);

和

    else
        return this->right->Search(data);

函数可以通过以下方式使用单个 return 语句定义

bool Search( int data ) const
{
    return ( this->data == data ) || 
           ( this->data >= data ? this->left  && this->left->Search( data )
                                : this->right && this->right->Search( data ) );    
}

其实条件

this->data >= data

可以替代

this->data > data

【讨论】:

  • 谢谢弗拉德,我知道所有路径都需要返回。但是,如果代码与我帖子中的原始代码一样,会发生什么?它仍然为搜索提供正确的输出。
  • @Nothing_8484 存在未定义的行为。它似乎有效,因为结果在同一个寄存器中返回。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-21
  • 2021-03-06
  • 1970-01-01
  • 1970-01-01
  • 2021-04-11
相关资源
最近更新 更多