【发布时间】:2018-08-21 02:37:09
【问题描述】:
我必须从文件中读取数据并从 按读取顺序排列的值。因此;读取的第一个数字将是树的根。我必须尝试将数字存储在数组中。 当我将最后一个值读入 BST 后,我需要进行中序遍历,以升序输出前 10 个值,并将它们打印 10 到 5 个字符宽的字段中的一行。 .
我的输出很好,可以按升序打印所有整数,但我想在一行中打印 10 个整数。我被困在这里。谁能帮我解决这个问题?
我的代码:
struct Node
{
int key;
Node *left, *right;
};
int NumNodes = 0;
const int SIZE = 100;
Node data[SIZE];
Node* nNode(int value)
{
Node* temp = &data[NumNodes++];
temp->key = value;
temp->left = temp->right = NULL;
return temp;
}
void inorder(Node *root)
{
if (root != NULL)
{
inorder(root->left);
cout << root->key << setw(5) ;
inorder(root->right);
}
Node* insert(Node* node, int key)
{
if (node == NULL)
{
return nNode(key);
}
if (key < node->key)
{
node->left = insert(node->left, key);
}
else if (key > node->key)
{
node->right = insert(node->right, key);
}
return node;
}
int main()
{
int c,val,i=0;
string fileName;
Node *root = NULL;
ifstream infile;
cout << "Please enter the name of the file to open :";
cin >> fileName; // asks user to input filename
infile.open(fileName.c_str()); // opens file
if(!infile)
{
cerr << "An eror occurred while openieng the file.";
exit(1);
}
while(!infile.eof()){
infile >> val;
data[i].key = val;
c=data[i].key;
root = insert(root, c);
i++;
}
infile.close();
inorder(root);
return 0;
}
【问题讨论】:
-
该程序包含一个错误,为了修复错误,您首先必须通过调试找到它。您可以通过使用 IDE 的调试器来做到这一点,或者(如果您手边没有调试器)您可以将
cout << __LINE__ << std::endl;之类的语句放在不同的位置并重新运行您的程序,直到找到导致崩溃的行(通过查看要打印的最后一个行号)。一旦您知道哪一行代码导致崩溃,您就需要检查该行以找出原因——很可能它试图取消引用 NULL 或其他无效指针。 -
你真的应该问一个不同的问题,而不是把这个问题变成三个。您的
inorder函数未包含在您的示例中,因此很难就无法看到的代码提供建议。也许阅读一些关于%做什么的文档。 -
我不能按照团队的建议。另外,我的
inorder已经包含在函数中了 -
我已经包含了
inorder,但我试图在每行打印出 10 个数字,这就是问题所在。 -
我的问题已经得到了低评价,因为发布了两个标题相同的问题,这就是为什么我必须更改标题才能让它发挥作用
标签: c++ arrays struct binary-search-tree