我正在尝试用C ++实现DS,这是带有插入和搜索功能的Binary Search Tree Class的简单实现。代码编译并根据需要提供输出。代码审查人员指出,搜索功能会发出警告,并且搜索功能中的代码已损坏。该警告类似于“并非所有控制路径都具有return语句”,但我认为这就是递归函数的样子。警告是否有问题,我该如何解决?另外,代码如何被破坏?谢谢。
#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;
}
此功能搜索在这些路径中不返回任何内容
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