struct node{
int element;
node* left;
node* right;
};
typedef node* SET;
void INSERT(int x, SET* A){
node* pA = *A;
if (pA == NULL){
pA = new node;
pA->element = x;
pA->left = NULL;
pA->right = NULL;
}
else{
if (x < pA->element){
INSERT(x,&(pA->left));
}
else if (x>pA->element){
INSERT(x, &(pA->right));
}
}
}
int main(){
node* A = NULL;
INSERT(1,&A);
cout <<A->element<<endl;
return 0;
}
The Code above is a simple insertion method that will insert an element into the BST. I just keep getting segment default when I access A->element. Many Thanks from your answer.
Edit:
wow, this pointer stuff is really confusing. So when I do node* pA = *A, I thought I would create a pointer pointing to the location of A. Then when I do pA = new node, it would create a node object in the heap pointing by pA which is the same as A. Am I saying anything wrong?
Consider using C++ references.
References allow the
AinINSERTand theAinmainto represent the same data, reducing pointer confusion.