-
Notifications
You must be signed in to change notification settings - Fork 0
/
BST.cpp
99 lines (76 loc) · 1.55 KB
/
BST.cpp
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
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
struct Node{
struct Node *left;
struct Node *right;
int data;
};
struct Node *createNewNode(int data){
struct Node *temp = (struct Node*) malloc(sizeof(struct Node));
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
};
struct Node* insertBST(struct Node *node, int data){
if(node == NULL)
return createNewNode(data);
if(data < node->data)
node->left = insertBST(node->left, data);
else if(data > node->data)
node->right = insertBST(node->right, data);
return node;
}
void preorder(struct Node *root, FILE *output, int last){
if(root != NULL){
if(last == 0){
fprintf(output,"%d",root->data);
preorder(root->left,output,1);
preorder(root->right,output,1);
}
else{
fprintf(output,", %d",root->data);
preorder(root->left,output,1);
preorder(root->right,output,1);
}
}
}
int main(int argc, char *argv[]){
FILE *input;
FILE *output;
struct Node *root = NULL;
int data, count=0;
char ch;
input = fopen(argv[1],"r");
if(input==NULL)
return -1;
output = fopen(argv[2],"w");
if(output==NULL)
return -1;
while(!feof(input)){
do{
fscanf(input,"%d%c ",&data,&ch);
//cout<<"data = "<<data<<"\n";
if(count == 0){
root = insertBST(root, data);
preorder(root,output,0);
fprintf(output,"\n");
count = 1;
}
else{
insertBST(root, data);
preorder(root,output,0);
fprintf(output,"\n");
}
}while(ch==',');
count=0;
fprintf(output,"\n");
}
fclose(input);
fclose(output);
return 0;
}