C++ Binary Search Tree status access violation error with adding nodes - c++

I'm working on a program that works with a binary tree. I'm getting an error with adding new nodes into the tree. I can add one node, but after adding another, I get a STATUS_ACCESS_VIOLATION error. I think the error could be with the function arguments dealing with the search function. Please help me if you can.
Here is he .h file that i've written:
#ifndef P4_H
#define P4_H
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cctype>
#include <string>
using namespace std;
struct TreeNode //ListNode structure with components
{
int acctNum;
TreeNode *left;
TreeNode *right;
};
typedef TreeNode* nodePtr; //defines a pointer to a treenode struct
class Tree
{
private:
nodePtr root;
int numElements;
public:
Tree()
{ root = NULL; numElements = 0; }
bool treeEmpty()
{ return (numElements == 0); }
void addNode()
{
int key;
cout << "Enter account number to add: ";
cin >> key;
cout << endl << endl;
nodePtr location = NULL, parent = NULL, p = NULL;
bool found = searchTree(key, &location, &parent);
cout << found << " " << location << " " << parent << endl << endl;
if (found)
{
cout << "Error! Account number: " << key << " already exists within"
<< " the tree." << endl << endl;
}
else
{
if (parent == NULL)
{
root = new TreeNode;
root->acctNum = key;
}
else
{
if (parent->acctNum > key)
{
parent->left = new TreeNode;
p = parent->left;
p->acctNum = key;
}
else
{
parent->right = new TreeNode;
p = parent->right;
p->acctNum = key;
}
}
}
}
bool searchTree(int key, nodePtr *location, nodePtr *parent)
{
bool found = false;
nodePtr p = root;
*location = root;
parent = NULL;
while (p != NULL && !found)
{
*location = p;
if (key == p->acctNum)
found = true;
else if (key < p->acctNum)
{
*parent = p;
p = p->left;
}
else if (key > p->acctNum)
{
*parent = p;
p = p->right;
}
}
return found;
}
void deleteNode()
{
int key;
nodePtr location = NULL, parent = NULL;
cout << "Enter account number to delete: ";
cin >> key;
cout << endl << endl;
bool found = searchTree(key, &location, &parent);
if (!found)
{
cout << "Error! Account number: " << key << " was not found."
<< endl << endl;
}
else if (location->left != NULL && location->right != NULL)
{ //delete node with left and right subtrees
nodePtr leftmost = location->right, leftmostParent = NULL;
while (leftmost->left != NULL)
{
leftmostParent = leftmost;
leftmost = leftmost->left;
}
leftmost->left = location->left;
leftmost->right = location->right;
leftmostParent->left = NULL;
if (parent->acctNum > location->acctNum)
parent->left = leftmost;
else
parent->right = leftmost;
delete location;
location = NULL;
}
else if (location->left != NULL && location->right == NULL)
{ //delete node with only a left subtree
if (parent->acctNum > location->acctNum)
parent->left = location->left;
else
parent->right = location->left;
delete location;
location = NULL;
}
else if (location->left == NULL && location->right != NULL)
{ //delete node with only a right subtree
nodePtr leftmost = location->right, leftmostParent = NULL;
while (leftmost->left != NULL)
{
leftmostParent = leftmost;
leftmost = leftmost->left;
}
leftmost->right = location->right;
leftmostParent->left = NULL;
if (parent->acctNum > location->acctNum)
parent->left = leftmost;
else
parent->right = leftmost;
delete location;
location = NULL;
}
else
{ //delete a leaf node
if (location->acctNum > parent->acctNum)
parent->right = NULL;
else
parent->left = NULL;
delete location;
location = NULL;
}
}
void displayAscend(nodePtr p, int count)
{
if (p->left != NULL)
displayAscend(p->left, count);
cout << count << ". " << p->acctNum << endl;
count ++;
if (p->right != NULL)
displayAscend(p->right, count);
}
void displayDescend(nodePtr p, int count)
{
if (p->right != NULL)
displayAscend(p->right, count);
cout << count << ". " << p->acctNum << endl;
count ++;
if (p->left != NULL)
displayAscend(p->left, count);
}
void readFile()
{
char filename[50];
cout << "Enter name of file to open: ";
cin.getline(filename,51);
cout << endl << endl;
ifstream inFile;
inFile.open(filename);
while (!inFile)
{
cout << "Error opening file! Please try again." << endl << endl;
cout << "Enter name of file: ";
cin.getline(filename,51);
cout << endl << endl;
}
int num;
while (!inFile.eof())
{
inFile >> num;
nodePtr location = NULL, parent = NULL, p = NULL;
bool found = searchTree(num, &location, &parent);
if (found)
{
cout << "Error! Account number: " << num << " already exists"
<< " within the tree." << endl << endl;
}
else
{
if (parent == NULL)
{
root = new TreeNode;
root->acctNum = num;
}
else
{
if (parent->acctNum > num)
{
parent->left = new TreeNode;
p = parent->left;
p->acctNum = num;
}
else
{
parent->right = new TreeNode;
p = parent->right;
p->acctNum = num;
}
}
}
}
}
};
#endif

In searchTree, you set parent to NULL before the loop, then dereference it in the loop.

Related

C++ How do I fix Exception thrown: write access violation. this was nullptr. on Line 20

*Create a simple linked list program to create a class list containing
class node {
void *info;
node *next;
public:
node (void *v) {info = v; next = 0; }
void put_next (node *n) {next = n;}
node *get_next ( ) {return next;}
void *get_info ( ) {return info;}
};
Be able to initially fill the list. Provide functions to insert/append nodes and remove nodes from the linked list. Be able to display the contents of the list.
Write a little driver program with at least 5 values passed in (so that 5 nodes are created) as you insert/append, delete and display data, showing the programs operation.
Output: While displaying the data, make sure you use an informational label–using the terms “insert”, “append”, “remove” and any other term which displays the action. All data that is displayed must be displayed in a way in which the mentor can easily read and understand.*
My code runs but it throws Exception thrown: write access violation. this was nullptr. on Line 20 when I debug it. In the output it also stops at Delete 04 of my list and outputs no further data after line 156. I am not sure how to fix this. I tried to force it to output the new list with another cout statement but that did not work. Any assistance would be appreciated. Entire code below.
#include <iostream>
#include <iomanip>
using namespace std;
class Node
{
void* info;
Node* next;
public:
Node(void* v) { info = v; next = 0; }
void put_next(Node* n)
{
next = n;
}
Node* get_next()
{
return next;
}
void* get_info()
{
return info;
}
};
class List {
Node* head;
public:
List() { head = NULL; };
void PRINT();
void APPEND(void* info);
void DELETE(void* info);
};
void List::PRINT() {
Node* temp = head;
if (temp == NULL)
{
cout << "Enter Values" << endl;
return;
}
if (temp->get_next() == NULL)
{
cout << *(int*)temp->get_info();
cout << " => ";
cout << "Invalid" << endl;
}
else
{
while (temp != NULL)
{
cout << *(int*)temp->get_info();
cout << " --> ";
temp = temp->get_next();
}
cout << "Invalid" << endl;
}
}
void List::APPEND(void* info) {
Node* newNode = new Node(info);
newNode->put_next(NULL);
Node* temp = head;
if (temp != NULL)
{
while (temp->get_next() != NULL)
{
temp = temp->get_next();
}
temp->put_next(newNode);
}
else
{
head = newNode;
}
}
void List::DELETE(void* info) {
Node* temp = head;
if (temp == NULL)
{
cout << "Enter Values" << endl;
return;
}
if (temp->get_next() == NULL)
{
if ((int*)(temp->get_info()) == info)
{
delete temp;
head = NULL;
}
}
else
{
Node* previous = NULL;
while (temp != NULL)
{
if ((int*)(temp->get_info()) == info) break;
previous = temp;
temp = temp->get_next();
}
previous->put_next(temp->get_next());
delete temp;
}
}
int main()
{
List list;
int a = 04;
int b = 11;
int c = 12;
int d = 15;
int e = 29;
int* Node1 = &a;
int* Node2 = &b;
int* Node3 = &c;
int* Node4 = &d;
int* Node5 = &e;
cout << "Append: 04" << endl;
list.APPEND(Node1);
cout << "Append: 11" << endl;
list.APPEND(Node2);
cout << "Append: 12" << endl;
list.APPEND(Node3);
cout << "Append: 15" << endl;
list.APPEND(Node4);
cout << "Append: 29" << endl;
list.APPEND(Node5);
cout << endl << "Print List" << endl;
list.PRINT();
cout << endl << "Delete 04" << endl;
list.DELETE(Node1);
list.PRINT();
cout << "Start New List" << endl;
cout << endl << "Delete 12" << endl;
list.DELETE(Node3);
list.PRINT();
return 0;
}
SOLUTION:
//Node.h
#pragma once
class Node
{
void* info;
Node* next;
public:
Node(void* v) { info = v; next = 0; }
void put_next(Node* n)
{
next = n;
}
Node* get_next()
{
return next;
}
void* get_info()
{
return info;
}
};
//List.h
#pragma once
#include "Node.h"
#include <iomanip>
class List {
Node* head;
public:
List() { head = NULL; };
void PRINT();
void APPEND(void* info);
void DELETE(void* info);
};
//List.cpp
#include <iostream>
#include "List.h"
using namespace std;
void List::PRINT() {
Node* temp = head;
if (temp == NULL)
{
cout << "Enter Values" << endl;
return;
}
if (temp->get_next() == NULL)
{
cout << *(int*)temp->get_info();
cout << " => ";
cout << "Invalid" << endl;
}
else
{
while (temp != NULL)
{
cout << *(int*)temp->get_info();
cout << " --> ";
temp = temp->get_next();
}
cout << "Invalid" << endl;
}
}
void List::APPEND(void* info) {
Node* newNode = new Node(info);
newNode->put_next(NULL);
Node* temp = head;
if (temp != NULL)
{
while (temp->get_next() != NULL)
{
temp = temp->get_next();
}
temp->put_next(newNode);
}
else
{
head = newNode;
}
}
void List::DELETE(void* info) {
Node* temp = head;
if (temp == NULL)
{
cout << "Enter Values" << endl;
return;
}
if (temp->get_next() == NULL)
{
if ((int*)(temp->get_info()) == info)
{
delete temp;
head = NULL;
}
}
else
{
Node* previous = NULL;
while (temp != NULL)
{
if ((int*)(temp->get_info()) == info) {
// if node is head then changing the head
if (temp == head)
head = temp->get_next();
break;
}
previous = temp;
temp = temp->get_next();
}
// skip this operation if node is head
if (temp->get_next() != head)
previous->put_next(temp->get_next());
delete temp;
}
}
//Main.cpp
#include <iostream>
#include "List.h"
using namespace std;
int main()
{
List list;
int a = 04;
int b = 11;
int c = 12;
int d = 15;
int e = 29;
int* Node1 = &a;
int* Node2 = &b;
int* Node3 = &c;
int* Node4 = &d;
int* Node5 = &e;
cout << "Append: 04" << endl;
list.APPEND(Node1);
cout << "Append: 11" << endl;
list.APPEND(Node2);
cout << "Append: 12" << endl;
list.APPEND(Node3);
cout << "Append: 15" << endl;
list.APPEND(Node4);
cout << "Append: 29" << endl;
list.APPEND(Node5);
cout << endl << "Print List" << endl;
list.PRINT();
cout << endl << "Delete 04" << endl;
list.DELETE(Node1);
list.PRINT();
cout << "Start New List" << endl;
cout << endl << "Delete 12" << endl;
list.DELETE(Node3);
list.PRINT();
return 0;
}
So whenever you are deleting first node, you missed to set the head to the next node of head.
Commented at the parts which are modified in the else statement of DELETE function
Code:
else
{
Node* previous = NULL;
while (temp != NULL)
{
if ((int*)(temp->get_info()) == info){
// if node is head then changing the head
if (temp == head)
head = temp->get_next();
break;
}
previous = temp;
temp = temp->get_next();
}
// skip this operation if node is head
if (temp->get_next() != head)
previous->put_next(temp->get_next());
delete temp;
}

Binary search tree C++ need the search and display functions to work

Need a void function Display that will display the binary search tree in tree shape
Need a value return or void function Search that will search for a specific data.
Not really sure What to do from this point except trial and error and trying to read off of others code...
I need help
Help
Here is my code...
class BinarySearchTree
{
private:
struct tree_node
{
tree_node* left;
tree_node* right;
int data;
};
tree_node* root;
public:
BinarySearchTree()
{
root = NULL;
}
bool isEmpty() const { return root == NULL; }
void print_inorder();
void inorder(tree_node*);
void print_preorder();
void preorder(tree_node*);
void print_postorder();
void postorder(tree_node*);
void insert(int);
void remove(int);
bool Search(int, tree_node*);
void Display(tree_node*, int);
};
int main()
{
BinarySearchTree b;
int ch, tmp, tmp1;
while (1)
{
system("cls");
cout << endl << endl;
cout << " Binary Search Tree Operations " << endl;
cout << " ----------------------------- " << endl;
cout << " 1. Insertion/Creation " << endl;
cout << " 2. In-Order Traversal " << endl;
cout << " 3. Pre-Order Traversal " << endl;
cout << " 4. Post-Order Traversal " << endl;
cout << " 5. Removal " << endl;
cout << " 6. Display " << endl;
cout << " 7. Display Message From Creator " << endl;
cout << " 8. EXIT " << endl;
cout << " Enter your choice : ";
cin >> ch;
switch (ch)
{
case 1: cout << " Enter Number to be inserted : ";
cin >> tmp;
b.insert(tmp);
break;
case 2: cout << endl;
cout << " In-Order Traversal " << endl;
cout << " -------------------" << endl;
b.print_inorder();
break;
case 3: cout << endl;
cout << " Pre-Order Traversal " << endl;
cout << " -------------------" << endl;
b.print_preorder();
break;
case 4: cout << endl;
cout << " Post-Order Traversal " << endl;
cout << " --------------------" << endl;
b.print_postorder();
break;
case 5: cout << " Enter data to be deleted : ";
cin >> tmp1;
b.remove(tmp1);
break;
case 6: cout << " Enter data to be deleted : ";
b.Display(NULL, tmp);
break;
case 7: cout << " I think you are a great person. Smile be happy ";
case 8:
return 0;
}
}
}
bool BinarySearchTree::Search(int d, tree_node* curr){
if (curr == NULL) {
return 0;
}
if (curr->data == d) {
return 1;
}
if (d > curr->data) {
return Search(d, curr->right);
}
else {
return Search(d, curr->left);
}
}
// Smaller elements go left
// larger elements go right
void BinarySearchTree::insert(int d)
{
tree_node* t = new tree_node;
tree_node* parent;
t->data = d;
t->left = NULL;
t->right = NULL;
parent = NULL;
// is this a new tree?
if (isEmpty()) root = t;
else
{
//Note: ALL insertions are as leaf nodes
tree_node* curr;
curr = root;
// Find the Node's parent
while (curr)
{
parent = curr;
if (t->data > curr->data) curr = curr->right;
else curr = curr->left;
}
if (t->data < parent->data)
parent->left = t;
else
parent->right = t;
}
}
void BinarySearchTree::remove(int d)
{
//Locate the element
bool found = false;
if (isEmpty())
{
cout << " This Tree is empty! " << endl;
return;
}
tree_node* curr;
tree_node* parent;
curr = root;
while (curr != NULL)
{
if (curr->data == d)
{
found = true;
break;
}
else
{
parent = curr;
if (d>curr->data) curr = curr->right;
else curr = curr->left;
}
}
if (!found)
{
cout << " Data not found! " << endl;
return;
}
// 3 cases :
// 1. We're removing a leaf node
// 2. We're removing a node with a single child
// 3. we're removing a node with 2 children
parent = NULL;
// Node with single child
if ((curr->left == NULL && curr->right != NULL) || (curr->left != NULL
&& curr->right == NULL))
{
if (curr->left == NULL && curr->right != NULL)
{
if (parent->left == curr)
{
parent->left = curr->right;
delete curr;
}
else
{
parent->right = curr->right;
delete curr;
}
}
else // left child present, no right child
{
if (parent->left == curr)
{
parent->left = curr->left;
delete curr;
}
else
{
parent->right = curr->left;
delete curr;
}
}
return;
}
//We're looking at a leaf node
if (curr->left == NULL && curr->right == NULL)
{
if (parent->left == curr) parent->left = NULL;
else parent->right = NULL;
delete curr;
return;
}
//Node with 2 children
// replace node with smallest value in right subtree
if (curr->left != NULL && curr->right != NULL)
{
tree_node* chkr;
chkr = curr->right;
if ((chkr->left == NULL) && (chkr->right == NULL))
{
curr = chkr;
delete chkr;
curr->right = NULL;
}
else // right child has children
{
//if the node's right child has a left child
// Move all the way down left to locate smallest element
if ((curr->right)->left != NULL)
{
tree_node* lcurr;
tree_node* lcurrp;
lcurrp = curr->right;
lcurr = (curr->right)->left;
while (lcurr->left != NULL)
{
lcurrp = lcurr;
lcurr = lcurr->left;
}
curr->data = lcurr->data;
delete lcurr;
lcurrp->left = NULL;
}
else
{
tree_node* tmp;
tmp = curr->right;
curr->data = tmp->data;
curr->right = tmp->right;
delete tmp;
}
}
return;
}
}
void BinarySearchTree::print_inorder()
{
inorder(root);
}
void BinarySearchTree::inorder(tree_node* p)
{
if (p != NULL)
{
if (p->left) inorder(p->left);
cout << " " << p->data << " ";
if (p->right) inorder(p->right);
}
else return;
}
void BinarySearchTree::print_preorder()
{
preorder(root);
}
void BinarySearchTree::preorder(tree_node* p)
{
if (p != NULL)
{
cout << " " << p->data << " ";
if (p->left) preorder(p->left);
if (p->right) preorder(p->right);
}
else return;
}
void BinarySearchTree::print_postorder()
{
postorder(root);
}
void BinarySearchTree::postorder(tree_node* p)
{
if (p != NULL)
{
if (p->left) postorder(p->left);
if (p->right) postorder(p->right);
cout << " " << p->data << " ";
}
else return;
}
void BinarySearchTree::Display(tree_node *curr, int indent)
{
if (curr != NULL)
{
cout << "My Tree. The left is top and right is bottom" << endl;
Display(curr->left, indent + 4);
if (indent > 0)
cout << setw(indent) << " ";
cout << curr->data << endl;
Display(curr->right, indent + 4);
}
}

Linked List Exception Thrown

I am new with linked lists and I am getting this error when trying to remove one of the nodes of a linked list.
Exception thrown: Exception thrown: read access violation.
std::_String_alloc<std::_String_base_types<char,std::allocator<char> > >::_Mysize(...) returned 0xDDDDDDF1. occurred
Code:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
struct node
{
string song, artist;
node* next;
};
node* add(node *head)
{
string song, artist;
cout << "Enter song name:" << endl;
getline(cin, song);
cout << "Enter artist name:" << endl;
getline(cin, artist);
node *new_ptr = new node;
new_ptr->song = song;
new_ptr->artist = artist;
if (head == nullptr)
{
head = new_ptr;
head->next = nullptr;
}
else
{
node *ptr = head;
while (ptr->next != nullptr)
{
ptr = ptr->next;
}
ptr->next = new_ptr;
ptr->next->next = nullptr;
}
cout << "Song added." << endl;
return head;
}
node* remove(node *head)
{
if (head == nullptr)
{
cout << "There are no songs." << endl;
return head;
}
string song_to_remove;
bool found = false;
cout << "Enter song name to remove:" << endl;
getline(cin, song_to_remove);
if (head->song.compare(song_to_remove) == 0)
{
found = true;
node *temp = head;
head = head->next;
delete temp;
}
else if(head->next != nullptr)
{
node *prev_ptr = head;
node *ptr = head->next;
while (ptr != nullptr)
{
if (ptr->song.compare(song_to_remove) == 0)
{
found = true;
node *temp = ptr;
prev_ptr->next = ptr->next;
delete temp;
}
ptr = ptr->next;
prev_ptr = prev_ptr->next;
}
}
if (!found)
{
cout << "Song not found." << endl;
}
else
{
cout << "Song removed." << endl;
}
return head;
}
void print(node *head)
{
node* ptr = head;
if (ptr == nullptr)
{
cout << "There are no songs added yet." << endl;
}
else
{
while (ptr != nullptr)
{
cout << ptr->song << " by " << ptr->artist << endl;
ptr = ptr->next;
}
}
}
int main()
{
node *head = nullptr;
int option;
while (1)
{
cout << "Choose an option: Add a song (1), remove a song (2), or list all the songs (3)." << endl;
cin >> option;
cin.ignore();
if (!(option == 1 || option == 2 || option == 3))
{
cout << "Must pick either 1, 2, or 3." << endl;
continue;
}
if (option == 1)
{
head = add(head);
}
else if (option == 2)
{
head = remove(head);
}
else if (option == 3)
{
print(head);
}
}
return 0;
}
I have everything working besides the remove() function, and it only errors when I have more than 1 item in the linked list and when I try to remove a node besides the first one.
I got it. I didn't have a break statement after deleting ptr and then was trying to assign something to ptr. I was trying to make it work so that if you had multiple songs with the same name it would delete all of them, but the program doesn't need to be that specific.
node* remove(node *head)
{
if (head == nullptr)
{
cout << "There are no songs." << endl;
return head;
}
string song_to_remove;
bool found = false;
cout << "Enter song name to remove:" << endl;
getline(cin, song_to_remove);
if (head->song == song_to_remove)
{
found = true;
node *temp = head;
head = head->next;
delete temp;
}
else if(head->next != nullptr)
{
node *prev_ptr = head;
node *ptr = head->next;
while (ptr != nullptr)
{
if (ptr->song == song_to_remove)
{
found = true;
prev_ptr->next = ptr->next;
delete ptr;
break;
}
ptr = ptr->next;
prev_ptr = prev_ptr->next;
}
}
if (!found)
{
cout << "Song not found." << endl;
}
else
{
cout << "Song removed." << endl;
}
return head;
}

Binary Search Tree Potentially Uninitiated Parent Pointer

I couldnt seem to resolve the unitialized local pointer "Parent". There isnt any other issue with this code other than the local pointer error I keep receiving Its driving me insane.
this is just me writing to post the simplest of questions
please aide me
I couldnt seem to resolve the unitialized local pointer "Parent". There isnt any other issue with this code other than the local pointer error I keep receiving Its driving me insane.
this is just me writing to post the simplest of questions
please aide me
//Binary Search Tree
#include <iostream>
#include <cstdlib>
using namespace std;
class BinarySearchTree
{
private:
struct tree_node
{
tree_node* left;
tree_node* right;
int data;
};
tree_node* root;
public:
BinarySearchTree()
{
root = NULL;
}
bool IsEmpty() const {
return root == NULL;
}
void print_inorder();
void inorder(tree_node*);
void print_preorder();
void preorder(tree_node*);
void print_postorder();
void postorder(tree_node*);
void insert(int);
void remove(int);
};
void BinarySearchTree::insert(int d)
{
tree_node* t = new tree_node;
tree_node* parent;
t->data = d;
t->left = NULL;
t->right = NULL;
parent = NULL;
if (IsEmpty()) root = t;
else
{
tree_node* curr;
curr = root;
while (curr)
{
parent = curr;
if (t->data > curr->data) curr = curr->right;
else curr = curr->left;
}
if (t->data < parent->data)
parent->left = t;
else
parent->right = t;
}
}
void BinarySearchTree::remove(int d)
{
tree_node* curr;
tree_node* parent;
bool found= false;
if (IsEmpty())
{
cout << " This Tree is Empty!" << endl;
return;
}
curr = root;
while (curr != NULL)
{
if (curr->data == d)
{
found = true;
break;
}
else {
parent = curr;
if (d > curr->data) curr = curr->right;
else curr = curr->left;
}
}
if (!found)
{
cout << " Data is not found!" << endl;
return;
}
if ((curr->left == NULL && curr->right != NULL) || (curr->left != NULL && curr->right == NULL))
{
if (curr->left == NULL && curr->right !=NULL)
{
if (parent -> left == curr)
{
parent->left = curr->right;
delete curr;
}
else {
parent->right = curr->right;
delete curr;
}
}
else //Left child
{
if (parent->left == curr)
{
parent->left = curr->left;
delete curr;
}
else
{
parent->right = curr->left;
delete curr;
}
}
return;
}
if (curr->left == NULL && curr->right == NULL)
{
if (parent->left == curr) parent->left = NULL;
else parent->right = NULL;
delete curr;
return;
}
//Node with 2 Children
if (curr->left != NULL && curr->right != NULL)
{
tree_node* chkr;
chkr = curr->right;
if ((chkr->left == NULL) && (chkr->right == NULL))
{
curr = chkr;
delete chkr;
curr->right = NULL;
}
else
{
if ((curr->right)->left != NULL)
{
tree_node* lcurr;
tree_node* lcurrp;
lcurrp = curr->right;
lcurr = (curr->right)->left;
while(lcurr ->left != NULL)
{
lcurrp = lcurr;
lcurr = lcurr->left;
}
curr->data = lcurr->data;
delete lcurr;
lcurrp->left = NULL;
}
else {
tree_node* tmp;
tmp = curr->right;
curr->data = tmp->data;
curr->right = tmp->right;
delete tmp;
}
}
return;
}
}
void BinarySearchTree::print_inorder()
{
inorder(root);
}
void BinarySearchTree::inorder(tree_node* p)
{
if (p != NULL)
{
if (p->left) inorder(p->left);
cout << " " << p->data << " ";
if (p->right) inorder(p->right);
}
else return;
}
void BinarySearchTree::print_preorder()
{
preorder(root);
}
void BinarySearchTree::preorder(tree_node* p)
{
if (p != NULL)
{
cout << " " << p->data << " ";
if (p->left)preorder(p->left);
if (p->right) preorder(p->right);
}
else return;
}
void BinarySearchTree::postorder(tree_node* p)
{
if (p != NULL)
{
if (p->left) postorder(p->left);
if (p->right) postorder(p->right);
cout << " " << p->data << " ";
}
else return;
}
int main()
{
BinarySearchTree b;
int ch, tmp, tmp1;
while (1)
{
cout << endl << endl;
cout << " Binary Search Tree Operations " << endl;
cout << "---------------------------------" << endl;
cout << " 1. Insertion/Creation " << endl;
cout << " 2. In-Order Traversal " << endl;
cout << " 3. Pre-Order Traversal " << endl;
cout << " 4. Post-Order Traversal " << endl;
cout << " 5. Removal " << endl;
cout << " 6. Exit " << endl;
cout << " Enter your choice: ";
cin >> ch;
switch (ch)
{
case 1: cout << "Enter Number to be Inserted: ";
cin >> tmp;
b.insert(tmp);
break;
case 2: cout << endl;
cout << " In-Order Traversal: " << endl;
cout << "---------------------" << endl;
b.print_inorder();
break;
case 3: cout << endl;
cout << " Pre-Order Traversal: " << endl;
cout << "------------------------" << endl;
b.print_preorder();
break;
case 4: cout << endl;
cout << " Post-Order Traversal: " << endl;
cout << "--------------------------" << endl;
b.print_postorder();
break;
case 5: cout << " Enter data to be deleted: ";
cin >> tmp1;
b.remove(tmp1);
break;
case 6: system("pause");
return 0;
break;
}
}
}
tree_node* parent;
You declare parent but never assign it a tree_node memory address to point to. Thus, performing operations on it or accessing its members (like parent->left) will cause issues, and raise the error you are getting.
Solution: Assign a value to parent before accessing it's members.

How to fix segmentation error 11 in c++

I am currently writing a binary tree project in c++ and it is giving me some errors that I am struggling to understand. The error in question is a segmentation error that I have no idea how to fix. Below is the code from one one the files where all the functions are written. The function in particular that is giving me an issue is the last one - the print_pre_order_private function.
#include <iostream>
#include <cstdlib>
#include "BT.h"
using namespace std;
BT::BT()
{
root = NULL; //makes sure pointer isn't pointing at anything
}
BT::node* BT::create_leaf(int key)
{
node* n = new node;
n->key = key;
n->left = NULL;
n->right = NULL;
return n;
}
void BT::add_leaf(int key)
{
add_leaf_private(key, root);
}
void BT::add_leaf_private(int key, node* Ptr)
{
if(root == NULL)
{
root = create_leaf(key);
}
else if(key < Ptr->key)
{
if(Ptr->left != NULL)
{
add_leaf_private(key, Ptr->left);
}
else
{
Ptr->left = create_leaf(key);
}
}
else if(key > Ptr->key)
{
if(Ptr->right != NULL)
{
add_leaf_private(key, Ptr->right);
}
else
{
Ptr->right = create_leaf(key);
}
}
else
{
cout << "The key " << key << " has already been added to the tree\n";
}
}
void BT::print_in_order()
{
print_in_order_private(root);
}
void BT::print_in_order_private(node* Ptr)
{
if(root != NULL)
{
if(Ptr->left != NULL)
{
print_in_order_private(Ptr->left);
}
cout << Ptr->key << " ";
if(Ptr->right != NULL)
{
print_in_order_private(Ptr->right);
}
}
else
{
cout << "The tree is empty\n";
}
}
BT::node* BT::return_node(int key)
{
return return_node_private(key, root);
}
BT::node* BT::return_node_private(int key, node* Ptr)
{
if(Ptr != NULL)
{
if(Ptr->key == key)
{
return Ptr;
}
else
{
if(key < Ptr->key)
{
return return_node_private(key, Ptr->left);
}
else
{
return return_node_private(key, Ptr->right);
}
}
}
else
{
return NULL;
}
}
int BT::return_root_key()
{
if(root != NULL)
{
return root->key;
}
else
{
return -1;
}
}
void BT::print_children(int key)
{
node* Ptr = return_node(key);
if(Ptr != NULL)
{
cout << "Parent Node = " << Ptr->key << endl;
Ptr->left == NULL ?
cout << "Left child = NULL\n":
cout << "Left child = " << Ptr->left->key << endl;
Ptr->right == NULL ?
cout << "Right child = NULL\n":
cout << "Right child = " << Ptr->right->key << endl;
}
else
{
cout << "Key " << key << " is not in the tree\n";
}
}
int BT::find_smallest()
{
return find_smallest_private(root);
}
int BT::find_smallest_private(node* Ptr)
{
if(root == NULL)
{
cout << "The tree is empty\n";
return -1;
}
else
{
if(Ptr->left != NULL)
{
return find_smallest_private(Ptr->left);
}
else
{
return Ptr->key;
}
}
}
void BT::remove_node(int key)
{
remove_node_private(key, root);
}
void BT::remove_node_private(int key, node* parent)
{
if(root != NULL)
{
if(root->key == key)
{
remove_root_match();
}
else
{
if(key < parent->key && parent->left != NULL)
{
parent->left->key == key ?
remove_match(parent, parent->left, true) :
remove_node_private(key, parent->left);
}
else if(key < parent->key && parent->right != NULL)
{
parent->right->key == key ?
remove_match(parent, parent->right, true) :
remove_node_private(key, parent->right);
}
else
{
cout << "The key " << key << " was not found in the tree\n";
}
}
}
else
{
cout << "The tree is empty\n";
}
}
void BT::remove_root_match()
{
if(root != NULL)
{
node* delPtr = root;
int root_key = root->key;
int smallest_right_subtree;
//case 0 - 0 children
if(root->left == NULL && root->right == NULL)
{
root = NULL;
delete delPtr;
}
//case 1 - 1 child
else if(root->left == NULL && root->right != NULL)
{
root = root->right;
delPtr->right = NULL;
delete delPtr;
cout << "The root node with key " << root_key << " was deleted. "
<< " The new root contains key " << root->key << endl;
}
else if(root->right == NULL && root->left != NULL)
{
root = root->left;
delPtr->left = NULL;
delete delPtr;
cout << "The root node with key " << root_key << " was deleted. "
<< " The new root contains key " << root->key << endl;
}
//case 2 - 2 children
else
{
smallest_right_subtree = find_smallest_private(root->right);
remove_node_private(smallest_right_subtree, root);
root->key = smallest_right_subtree;
cout << "The rout key containing key " << root_key
<< " was overwritten with key " << root->key << endl;
}
}
else
{
cout << "Cannot remove root. Tree is empty\n";
}
}
void BT::remove_match(node* parent, node* match, bool left)
{
if(root != NULL)
{
node* delPtr;
int match_key = match->key;
int smallest_right_subtree;
//case 0 - 0 children
if(match->left == NULL && match->right == NULL)
{
delPtr = match;
left == true ? parent->left = NULL : parent->right = NULL;
delete delPtr;
cout << "The node containing key " << match_key << " was removed\n";
}
//case 1 - 1 child
else if(match->left == NULL && match->right != NULL)
{
left == true ? parent->left = match->left : parent->right = match->right;
match->left = NULL;
delPtr = match;
delete delPtr;
cout << "The node containing key " << match_key << " was removed\n";
}
//case 2 - 2 children
else
{
smallest_right_subtree = find_smallest_private(match->right);
remove_node_private(smallest_right_subtree, match);
match->key = smallest_right_subtree;
}
}
else
{
cout << "Cannot remove match. The tree is empty";
}
}
void print_pre_order()
{
print_pre_order_private(root);
}
void print_pre_order_private(node* Ptr)
{
if(root != NULL)
{
cout << Ptr->key << " ";
print_pre_order_private(Ptr->left);
print_pre_order_private(Ptr->right);
}
}
Any help in fixing this situation is greatly appreciated. Thanks in advance. :)
In print_pre_order_private(node* Ptr) function. Shouldn't this be "if(Ptr != NULL)" instead of "if(root != NULL)" ?. I think there is the crash.
Since you have designed "print_pre_order_private()" function as a recursive function you should check for the validity of "Ptr" instead of always checking for the validity of "root", since the left/right/both of the child may be NULL at the very bottom of the tree depending on your input.