Hi,
I am trying to build a BST. I have so far this code and I must have made a mistake somewhere with the pointers, but I could not figure out where. So when I run it it says: "Segmentation fault (core dumped).
Here is the code:
Code:
//BTree#include <iostream>
using namespace std;
//BTree struct
struct BTree{
int data;
BTree* left;
BTree* right;
};
//BTree new node
BTree* BTree_NewNode(int inputData){ //inputData = new entry in console
BTree* node=new BTree;
node->data=inputData;
node->left=NULL;
node->right=NULL;
return(node);
};//BTree new node end
BTree* BTree_Insert(BTree* node, int inputData){
if(node==NULL){
return(BTree_NewNode(inputData));
}else{
if(inputData<=(node->data)){
node->left=BTree_Insert(node->left,inputData);
}else{
node->right=BTree_Insert(node->right,inputData);
}
return(node); //else statemnet return
}
};//BTree_Insert end
//Print out BTree
void BTree_Print(BTree* node){
if((node->left)==NULL && (node->right)==NULL){
return;
}else{
if((node->left)!=NULL){
BTree_Print(node->left);
cout<<"Data: "<<node->data<<endl;
}
else{
BTree_Print(node->right);
cout<<"Data: "<<node->data<<endl;
}
}
}//end BTree_Print()
int main(){
BTree* root;
BTree_Insert(root,5);
BTree_Insert(root,2);
BTree_Insert(root,7);
BTree_Insert(root,8);
BTree_Insert(root,1);
BTree_Print(root);
return 0;//main return
}//main() end