[英]How to print Binary Search Tree in specific format C++
I have to read data from the file and construct a binary search tree from the values in the order they are read. 我必须从文件中读取数据,并按读取顺序从这些值构造一个二进制搜索树。 Thus;
从而; the first number read will be the root of the tree.
读取的第一个数字将是树的根。 I must attempt to store the numbers in an array.
我必须尝试将数字存储在数组中。 When I have read the last value into the BST, I need to conduct an in‐order traversal to output first 10 values in ascending order and Print them 10 to a line in a 5‐character wide field.
当我将最后一个值读入BST后,我需要进行有序遍历,以升序输出前10个值,并将它们打印10个到5个字符宽的行中。 .
。
My output is fine and printing all integers in ascending order but I want to print 10 integers in one line. 我的输出很好,并以升序打印所有整数,但我想在一行中打印10个整数。 I am stuck here.
我被困在这里。 Can anybody help me figure this one out ?
有人可以帮我解决这个问题吗?
My Code: 我的代码:
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;
}
void inorder(Node *root)
{
static int n=0;
if (root != NULL)
{
inorder(root->left);
cout << setw(5) << root->key;
if(n%10==9)cout << endl;
n++;
inorder(root->right);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.