Im trying to insert items into a BST from a txt file.
For arguments sake the data file is just the integers 1 2 3 4 5 6 7 8 9.
When i try to do a inorder traversal, all that is outputting is the first and last number.
I think the problem is with the creating the BST though i'm not sure what it is?
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
struct BST
{
int data;
BST *left;
BST *right;
};
void menu(); //Displays menu options.
void buildBST(BST *& tree);
void printInorder(BST * p);
BST * tree = new BST;
int main()
{
cout << " Binary Search Tree Balancing and Drawing" << endl;
menu();
system("PAUSE");
return EXIT_SUCCESS;
}
void menu()
{
int choice;
cout << "\tMenu" << endl;
cout << " 1. Build new binary search tree" << endl;
cout << " 2. Display inorder traversal" << endl;
cout << " 3. Save tree (as preorder traversal)" << endl;
cout << " 4. Balance tree" << endl;
cout << " 5. Draw tree" << endl;
cout << " 6. Quit" << endl;
cout << " Choice ? ";
cin >> choice;
switch (choice)
{
case 1:
buildBST(tree);
break;
case 2:
printInorder(tree);
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
}
}
void buildBST(BST *& tree)
{
int array [100];
int index = 0;
int output;
int number; //To store a[i] in.
tree = NULL; //To ensure the tree is built fresh.
ifstream infile;
string fileName;
cout << "Please enter name of data file" << endl;
cin >> fileName;
infile.open(fileName.c_str());
if (!infile)
{
cout << "Cannot find " << fileName << endl;
cout << endl;
menu();
}
if (infile.is_open())
{
while (!infile.eof())
{
infile >> output;
array[index];
index++;
BST * t = new BST;
t -> data = output;
t -> left = NULL;
t -> right = NULL;
if (tree == NULL)
{
tree = t;
cout << "NULL = " << t -> data << endl;
}
else if (output < tree -> data)
{
tree -> left = t;
cout << "LEFT = " << t -> data << endl;
}
else // (output > tree -> data)
{
tree -> right = t;
cout << "RIGHT = " << t -> data << endl;
}
}
}
cout << endl;
menu();
}
void printInorder(BST * tree)
{
if (tree != NULL)
{
printInorder (tree -> left); // print left subtree
cout << tree -> data << endl; // print this node
printInorder (tree -> right); // print right subtree
}
}