I have a file of strings, each of which is in a separate line. I want to insert these strings to my treenodes. My codes can be compiled fine but when I load my string file, there is a segmentation fault. How do I fix it and are my codes correct to make a tree? If I want to remove each node and print it on screen, what would the remove function be? My header file:
#ifndef TREE_H
#define TREE_H
#include <iostream>
using namespace std;
struct TreeNode
{
string Key;
TreeNode *left;
TreeNode *right;
};
class Tree
{
private:
TreeNode *root;
public:
Tree();
~Tree();
string Insert(TreeNode *newNode);
string Delete(string Key);
private:
void ClearTree(TreeNode *T);
};
#endif
Here is my cpp file:
#include <iostream>
#include "try1.hxx"
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
Tree::Tree()
{
root = NULL;
}
Tree::~Tree()
{
ClearTree(root);
}
void Tree::ClearTree(TreeNode *T)
{
if(T==NULL) return;
if(T->left != NULL) ClearTree(T->left);
if(T->right != NULL) ClearTree(T->right);
delete T;
}
string Tree::Insert(TreeNode *newNode)
{
TreeNode *temp;
TreeNode *back;
temp = root;
back = NULL;
while(temp != NULL)
{
back = temp;
if(newNode->Key < temp->Key)
temp = temp->left;
else
temp = temp->right;
}
if(back == NULL) root = newNode;
else
{
if(newNode->Key < back->Key) back->left = newNode;
else back->right = newNode;
}
}
int main(int number_of_arguments, char** arguments)
{
Tree *theTree;
TreeNode *newNode;
theTree = new Tree();
string line;
if (number_of_arguments != 2)
{
cout << "ERROR: incorrect command line parameters" << endl;
}
ifstream myfile;
myfile.open (arguments[1]);
if (myfile.is_open())
{
while (getline(myfile, line))
{
newNode = new TreeNode();
newNode->Key=line;
newNode->left = newNode->right = NULL;
theTree->Insert(newNode);
}
}else cout << "The file doesn't exist" << endl;
}
Aucun commentaire:
Enregistrer un commentaire