Hello, everybody!
I'm writing a code, which should be able to insert a node to a binary tree where specified. Commands are being loaded from a .txt file.
The contents of the .txt file are the following:
1
L 1 2
R 1 3
L 2 6
R 2 4
L 3 5
R 3 7
F
first line stands for the root data
L stands for the left node
R stand for the right node
first digit stands for the data of a node to which a child must be added
second digit stands for the data of the child which is about to be inserted
That means that the command L 2 6 means "add a child with data '6' to a node with data '2'.
Here is the code i've written so far:
#include <iostream>
#include <fstream>
using namespace std;
struct node{
int data;
node *left;
node *right;
};
node *tree=NULL;
void add_node(node *tree, char how, int where, int what);
node *search(node *tree, int where);
node *search(node *some, int somewhere);
void print_inorder(node *tree);
int main(){
int start;
char how;
int where, what;
ifstream fin("test.txt");
fin>>start;
tree = new node;
tree->left=tree->right=NULL;
tree->data=start;
do {
fin>>how>>where>>what;
add_node(tree, how, where, what);
} while(how!='F');
print_inorder(tree);
system("pause");
return 0;
}
void add_node(node *tree, char how, int where, int what){
node *p=tree;
p=search(p, where);
if(p->data==where) {
if (how=='L'){
p->left=new node;
p->left->data=what;
p->left->left=p->left->right=NULL;
}
if (how=='R'){
p->right=new node;
p->right->data=what;
p->right->left=p->right->right=NULL;
}
}
return;
}
node *search(node *some, int somewhere){
if(some->data==somewhere) return some;
else{
search(some->left, somewhere);
search(some->right, somewhere);
}
}
void print_inorder(node *tree) {
if (tree!=NULL) {
print_inorder(tree->left);
cout<<tree->data<<endl;
print_inorder(tree->right);
}
}
The problem is that OS stops the execution with an error and the debugger says: An Access Violation (Segmentation fault) raised in your program. I would appreciate some help, thank you in advance.
P.S. When file contains only 3 commands, like
1
L 1 2
R 1 3
everything goes smooth.