问题描述
我制作了使用BST算法的程序来浏览包含50个整数值的文件,然后使用有序遍历显示它们
#include <iostream>
#include<fstream>
std::string fileName;
std::fstream readFile;
int storeFile;
struct Node {
int data;
Node* left;
Node* right;
};
struct bstNode {
int data;
bstNode* left;
bstNode* right;
};
bstNode* getnewNode(int data) {
bstNode* newNode = new bstNode();
(*newNode).data = data;
(*newNode).left = NULL;
(*newNode).right = NULL;
return newNode;
}
bstNode* Insert(bstNode* root,int data) {
if(root == NULL) {
root = getnewNode(data);
return root;
} else if( data <= root->data) {
root->left = Insert(root->left,data);
}
else {
root->right = Insert(root->right,data);
}
return root;
}
bool Search(bstNode* root,int data) {
if(root == NULL ) {
return false;
} else if(root->data == data) {
return true;
} else if(data <= root->data) {
return Search(root->left,data);
} else return Search(root->right,data);
}
void Inorder(bstNode* root) {
if(root==NULL) return;
Inorder(root->left);
std::cout << root->data << std::endl;
Inorder(root->right);
}
int main(int argc,char *argv[])
{
bstNode* root = NULL;
std::cout << "Please enter the name of the file: " << std::endl; //prompts user for the filename
std::cin >> argv[0]; //stores the filename is the first element of argv[]
fileName = argv[0];
std::cout << "Attempting to read file " << fileName << std::endl;
readFile.open(fileName); //attempts to read the file
if(!readFile) {
std::cerr << "ERROR: failed to open file " << std::endl; //if the file cannot be opened an error is displayed
exit(0); //if it cannot open the console terminates
} else {
std::cerr << "File successfully opened" << std::endl;
}
while(readFile >> storeFile){
if(readFile.bad()) {
std::cerr << "File failed to read " << std:: endl;
break; //loop terminates
} else {
root = Insert(root,storeFile);
}
Inorder(root);
}
readFile.close();
return 0;
}
程序可以正确编译并可以运行,但是我认为输出不正确
输入文件
1
12
10
7
2
9
4
100
输出
1
1
12
1
10
12
1
7
10
12
1
2
7
10
12
1
2
7
9
10
12
1
2
4
7
9
10
12
1
2
4
7
9
10
12
100
我知道此输出不正确,因为其输出太大。在我的程序中,使用BST会出错吗?谢谢
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)