Hi everyone,
So I have a binary tree class, Stree, that holds names of cities and pointers to other cities. Running the program and typing "insert Memphis Atlanta" inserts a node with Memphis, and inserts a node with Atlanta as Memphis's left child. Typing "insert Memphis Tampa" inserts a node with Tampa as Memphis's right child. Typing "insert" with two cities not already in the tree should generate an error, but when I try it, i get a seg fault.
The insert function runs a recursive function, searchInsert, that finds the city and sets a pointer to that city, target:
void Stree::searchInsert(string city1, bool &found, Node*& target, Node* root) {
//base case
if (root != NULL) {
searchInsert(city1, found, target, root->m_left);
if (root->city == city1) {
target = root;
found = true;
cout << "found city " << city1 << " at (" << root << ")" << endl;
}
searchInsert(city1, found, target, root->m_right);
}
}
Coming out of the recursion, insert proceeds to insert the new city somewhere:
//if the city has no current destinations
if (target->m_left == NULL) {
target->m_left = new Node(city2);
cout << "inserted " << city2 << " at (" << target->m_left << ")" << endl;
}
//if the city has 1 destination
else if (target->m_right == NULL) {
target->m_right = new Node(city2);
cout << "inserted " << city2 << " at (" << target->m_right << ")" << endl;
}
//if the city already has 2 destinations
else {
cerr << "Error: could not insert <" << city1 << ", " << city2 << ">";
errors = 1;
}
if (found == false) {
if (errors == 0) {
cerr << "Error: could not insert <" << city1 << ", " << city2 << ">";
}
}
Somewhere along the above code, when the function cannot find the city or there are 2 destinations already, it segs faults. And i cannot see why it would. Any help would be greatly appreciated.
Thanks!