Question: C++ Why am I getting a segmentation fault: 11? int main() { BinarySearchTree tree; NodeType *T; T = tree.insert(10,T); tree.preOrderPrint(T); } *********************************** struct NodeType {
C++
Why am I getting a segmentation fault: 11?
int main()
{
BinarySearchTree tree;
NodeType *T;
T = tree.insert(10,T);
tree.preOrderPrint(T);
}
***********************************
struct NodeType {
int key;
NodeType *lptr;
NodeType *rptr;
};
class BinarySearchTree{
public:
BinarySearchTree();
NodeType* insert(const int&, NodeType*);
void preOrderPrint(NodeType *root);
private:
NodeType* root;
};
BinarySearchTree::BinarySearchTree(){
root = NULL;
}
NodeType* BinarySearchTree::insert(const int& x, NodeType *root){
NodeType *n = new NodeType;
n->key = x;
n->lptr = n->rptr = NULL;
if(root == NULL)
root = n;
else {
NodeType *curr = root;
NodeType *prev;
while(curr != NULL) {
prev = curr;
if(x < curr->key)
curr = curr->lptr;
else
curr = curr->rptr;
}
if(x < prev->key)
prev->lptr = n;
else
prev->rptr = n;
}
return root;
}
void BinarySearchTree::preOrderPrint(NodeType *root) {
if(root!= NULL){
cout << root->key << endl;
preOrderPrint(root->lptr);
preOrderPrint(root->rptr);
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
