如何打印在二叉搜索树中找到的数据?

How to print data found in Binary Search Tree?

本文关键字:搜索树 数据 何打印 打印      更新时间:2023-10-16

我正在做这个程序,它读取一个CSV文件并将其输入到树中,到目前为止,我已经设法创建了树,它按顺序显示它们,但是在搜索中我失败了,因为它没有显示正在搜索的元素的信息,可以帮助我纠正错误的人, 谢谢。。。。

csv文件包含数据(包含几个,但我保留这些例如(:

1,名称1,数字1
2,名称2,数字2
3,名称3,数字3


#include <iostream>
#include <iomanip>
#include <fstream>
#include <memory>
#include <string>
#include <sstream>
#include <vector>
#include <utility>
#include <experimental/optional>
intmax_t dato;
struct Person {
intmax_t key;
std::string name;
intmax_t 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 <<  "tID: "<< root->key << "tName: "<< root->name << "ttNum: " << root->num << 'n'; //'t' ' '
inorder(root->right.get());
}
}

std::experimental::optional<Person> busqueda(Node *root, intmax_t dato) {
if(root==NULL){
return {};
}
else if(root->key==dato){
return *root;
}
else if(dato<root->key){
return busqueda(root->left.get(),dato);
}
else{
return busqueda(root->right.get(),dato);
}
}

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 = ',';
std::cout<<"ttDatan"<<std::endl;
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(10)<<"ID:   " << persons[i].key << std::setw(30)<<"Name:   "
<< persons[i].name << std::setw(20) <<"Num:   "<< persons[i].num << 'n';
if (!root) root = std::make_unique<Node>(persons[i]);
else root->insert(persons[i]);
}
std::cout << "nnttInorder:nn";
inorder(root.get());

std::cout<<" Enter data: "; std::cin>> dato;
busqueda(root.get(),dato);
if(busqueda(root.get(),dato)){
std::cout<<"Data found"<<std::endl;
std::cout<<root->name;//does not show the wanted, only the first of the document.
}
else{
std::cout<<"nData not found"<<std::endl;
}
return 0;
}

从注释中,您将搜索结果丢弃在以下语句中:

busqueda(root.get(),dato);返回一个可选值 std::experimental::optional,但您不使用该值。

您使用if(busqueda(root.get(),dato)){测试该值,但由于您没有存储结果,因此您都进行了第二次搜索,并且无法获取 Person 对象。

相反,您可以执行此操作来获取 person 对象并显示其名称:

std::cout << " Enter data: "; std::cin >> dato;
auto result = busqueda(root.get(), dato);
if (result) {
std::cout << "Data found" << std::endl;
std::cout <<result->name; // This should be the name of the found Person
}
else {
std::cout << "nData not found" << std::endl;
}