I need to know how to read in from a file and insert the information into a binary tree. The input file looks like this.
P L R
1 2 3
3 4 5
5 6 7
7 8 9
where P is the parent, L is the left child, and R is the right child.
Here is my treeNode class,
class treeNode
{
private:
int data;
treeNode *left;
treeNode *right;
public:
treeNode() {left = NULL; right = NULL;} //constructor
int get_data( ) { return data; } // 3 getters
treeNode* get_left( ) { return left; }
treeNode* get_right( ) { return right; }
void set_data(const int& new_data) { data = new_data; }
void set_left(treeNode* new_left) { left = new_left; }
void set_right (treeNode* new_right) { right = new_right; }
void insert(int num, treeNode * headPoint); // HERE IS MY PROBLEM
void inorder(treeNode *headPoint); //prints the tree in order
void preorder(treeNode *headPoint);// prints tree in preorder
void postorder(treeNode *headPoint); //prints tree in postorder
};
I can figure everything out but the insert function.
here is the implementation for the insert function
void treeNode::insert(int num, treeNode * headPoint)
{
if(headPoint != NULL)
insert(num, headPoint -> left);
else if(headPoint != NULL)
insert(num, headPoint -> right);
if(headPoint == NULL)
headPoint = new treeNode;
headPoint -> data = num;
}
it obviously doesn't work, or I wouldnt be here.
I have just been calling the function from a while loop like this int my main function,
In >> num;
while(In)
{
root.insert(num, headPTR);
cout << num << " ";
In >> num;
}
Reading from an input file to a tree
Page 1 of 11 Replies - 1230 Views - Last Post: 10 March 2008 - 10:30 AM
Replies To: Reading from an input file to a tree
#2
Re: Reading from an input file to a tree
Posted 10 March 2008 - 10:30 AM
I made a mistake on the input file... It looks like this
P L R
1 2 3
2 4 5
3 6 7
4 8 9
P L R
1 2 3
2 4 5
3 6 7
4 8 9
Page 1 of 1