writing BST to file

Hello
I have a complete code for creating binary search tree and prints out the numbers in the right order i just want to know how can i make the program write these numbers into outPutFile in the code. (You can put any numbers in the input file it wont matter, the program will sort them and put them in order, i just need someone to help me transfer these numbers into the output file)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
 #include <iostream>
#include <fstream>
using namespace std;


struct BstNode {
	int data;
	BstNode* left;
	BstNode* right;
};


BstNode* GetNewNode(int data) {
	BstNode* newNode = new BstNode();
	newNode->data = data;
	newNode->left = newNode->right = NULL;
	return newNode;
}

BstNode* Insert(BstNode* root, int data) {
	if (root == NULL) { 
		root = GetNewNode(data);
	}
	
	else if (data <= root->data) {
		root->left = Insert(root->left, data);
	}
	else {
		root->right = Insert(root->right, data);
	}
	return root;
}

void printPostorder(struct BstNode* node)
{
	if (node == NULL)
		return;

	printPostorder(node->left);

	
	printPostorder(node->right);

	
	printf("%d ", node->data);
}


void printInorder(struct BstNode* node)
{
	if (node == NULL)
		return;


	printInorder(node->left);

	
	printf("%d ", node->data);
	 
	
	printInorder(node->right);
}


void printPreorder(struct BstNode* node)
{
	if (node == NULL)
		return;

	
	printf("%d ", node->data);

	
	printPreorder(node->left);

	
	printPreorder(node->right);
}

int main()
{
	int Numbers[15];
	BstNode* root = NULL;
	ifstream inPutFile;
	ofstream outPutFile;

	inPutFile.open("Numbers.txt");
	outPutFile.open("Output.txt");

	//Reading numbers from the file to Numbers[]
	for (int i = 0; i < 15; i++)
	{
		inPutFile >> Numbers[i];
	}

	//Implementing BST to all Numbers[] values
	for (int i = 0; i < 15; i++)
	{
		root = Insert(root, Numbers[i]);
	}

	
	printPostorder(root);
	cout << endl;
	printPreorder(root);
	cout << endl;
	printInorder(root);




	system("PAUSE");
	return 0;
}
Last edited on

So if you want to print data to a file
data >> outPutFile;

The only problem I see is you have it defined in main, so you may have to define it in your function instead.
Topic archived. No new replies allowed.