I was working on Pre-order traverse Binary Tree algorithm. But I meet with Segmentation fault:11 error. The codes are shown as follow.
I want to know why this error happens. By the way, I have tried non-recursion algorithm preorder(),segmentation fault still happen.
The environment: macOS, clang-800.0.38
struct Node{
char val;
Node* left;
Node* right;
};
void preorder(Node *T){
if(T!=NULL){
cout << T->val;
preorder(T->left);
preorder(T->right);
}
}
int main(){
Node *T = (Node *)malloc(sizeof(Node));
Node *p = T;
p->val = 'A';
p->left = (Node *)malloc(sizeof(Node));
p->left->val = 'B';
p->right = (Node *)malloc(sizeof(Node));
p->right->val = 'C';
preorder(T);
return 0;
}
Nodemalloc-ed could have non-NULL left and right so yourpreorder()will incorrectly traverse into invalid memory location. As you are using C++, why don't you write a constructor for your class and usenew, instead of usingmalloc?