防弹站树搜索功能C++



该程序读取CSV文件并将其输入到二叉搜索树中。到目前为止,我已经设法插入了一个新节点,将其整理好,但是,在内部,执行搜索要求 Varibale 键,但我还没有设法让它工作,有人可以帮助我吗?

CSV 文件正在读取包含以下内容的文件:
1, 名称1,123456 2, 名称2,165151
3, 名称3,1566516


#include <iostream>
#include <iomanip>
#include <fstream>
#include <memory>
#include <string>
#include <sstream>
#include <vector>
struct Person {
int key;
std::string name;
int num;
};
struct Node : Person {
Node(const Person &person) : Person(person) {}
std::unique_ptr<Node> left, right;
void insert(const Person &person);
};
void Node::insert(const Person &person) {
/* recur down the tree */
if (key > person.key) {
if (left)
left->insert(person);
else
left = std::make_unique<Node>(person);
} else if (key < person.key) {
if (right)
right->insert(person);
else
right = std::make_unique<Node>(person);
}
}
std::vector<Person> persons;
void inorder(Node *root) {
if (root) {
// cout<<"t";
inorder(root->left.get());
std::cout << 't' << root->key << ' ' << root->name << ' ' << root->num << 'n';
inorder(root->right.get());
}
}
Node *minValueNode(Node *node) {
Node *current = node;
/* loop down to find the leftmost leaf */
while (current && current->left) current = current->left.get();
return current;
}

int main() {
std::unique_ptr<Node> root;
std::ifstream fin("data.txt");
if (!fin) {
std::cout << "File not openn";
return 1;
}
std::string line;
const char delim = ',';
while (std::getline(fin, line)) {
std::istringstream ss(line);
Person person;
ss >> person.key;
ss.ignore(10, delim);
std::getline(ss, person.name, delim);
ss >> person.num;
if (ss) persons.push_back(person);
}
for (unsigned int i = 0; i < persons.size(); i++) {
std::cout << std::setw(5) << persons[i].key << std::setw(20)
<< persons[i].name << std::setw(15) << persons[i].num << 'n';
if (!root) root = std::make_unique<Node>(persons[i]);
else root->insert(persons[i]);
}
std::cout << "nnInorder:n";
//    cout<<node.name;
inorder(root.get());
return 0;
}

/*bool busqueda(Node *root, int dato)
{
if(root){
return false;
}
else if(root->key==dato){
return true;
}
else if(dato<root->key){
busqueda(root->left.get(),dato);
}
else{
return busqueda(root->right.get(),dato);
}
}*/

假设这是您需要帮助的函数:

bool busqueda(Node *root, int dato) {
if(root){
return false;
}
else if(root->key==dato){
return true;
}
else if(dato<root->key){
busqueda(root->left.get(),dato);
}
else{
return busqueda(root->right.get(),dato);
}
}

这里有几个问题:

if(root) {

这是测试root是否nullptr,所以如果root指向某事,您将立即保释。 这意味着,如果提供了任何树,您将立即返回 false,这与您想要的相反。 更糟糕的是,如果rootnull,您将继续并尝试取消引用 null 指针,这将使程序崩溃。 将此行更改为if (root != nullptr) {

else if(dato<root->key){
busqueda(root->left.get(),dato);
}

这个递归调用看起来是正确的,除了你不返回结果,这意味着你将到达返回bool的函数的末尾,而实际上没有返回任何有意义的东西。 只需在此函数调用之前添加return即可。

您也可以主要使用布尔逻辑来表达此函数:

bool busqueda(Node *root, int dato) {
return root != nullptr && (
root->key == dato ||
busqueda((dato < root->key ? root->left : root->right).get(), dato)
);
}

这使得忘记归还某些东西是不可能的。

作为旁注,启用所有编译器警告 - 它会警告您到达非 void 函数的末尾而不返回值。

最新更新