我正在尝试用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<<"Foundn";
else
std::cout<<"Not Foundn";
return 0;
}
此函数Search在这些路径中不返回任何内容
else
this->left->Search(data);
和
else
this->right->Search(data);
你必须写
else
return this->left->Search(data);
和
else
return this->right->Search(data);
该函数可以通过以下方式用单个返回语句定义
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