Getting nullptr error when trying to delete a node from a binary tree

Hello,

I am trying to delete a node from a binary tree and am getting a nullptr error. If anyone would please give me some pointers on what to look for, I would greatly appreciate it.

The function is below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
  void BinTree::deleteItem(int val)
{
	MyNode *trailCurrent = nullptr;
	MyNode *current = root; //pointer to traverse the tree
	MyNode *temp;

	bool found = false;
	if (root == nullptr)
	{
		cout << "Cannot delete from the empty tree." << endl;
		return;
	}
	//find the node to be deleted
	while (current != nullptr && !found)
	{
		if (current->info == val)  //if value is found
			found = true;
		else  //while value is not found
		{
			trailCurrent = current;
			if (val < current->info)  //if value is less than current's info
				current = current->llink; //traverse the left side of the tree
			else
				current = current->rlink;  //otherwise traverse the right side of the tree
		}
	}

	if (current = nullptr)
		cout << "The item to be deleted is not in the tree." << endl;

	else if (found) //delete pointers to node
	{
		//node is a leaf
		trailCurrent = current;
		if (current->llink == NULL && current->rlink == NULL)
		{
			if (trailCurrent->llink == current)
				trailCurrent->llink = NULL;
			else
				trailCurrent->rlink = NULL;
			delete current;
		}
		//node has 2 children
		else if ((current->llink != NULL) && (current->rlink != NULL))
		{
	
			current = trailCurrent->llink;
//			trailCurrent = NULL;
			while (current->rlink != NULL)
			{
				trailCurrent = current;
				current = current->rlink;
			}
			trailCurrent->info = current->info;
			if (trailCurrent == NULL)
				trailCurrent->llink = current->llink;
			else
				trailCurrent->rlink = current->llink;
			delete current;
		}
		//node has 1 child
		else
		{
			if (trailCurrent->llink == NULL)
			{
				temp = trailCurrent;
				trailCurrent = temp->rlink;
				delete temp;
			}
			else
				temp = trailCurrent;
				trailCurrent = temp->llink;
				delete temp;
		}
	}
	
}


Thank you.

Regards,

Ragan
Last edited on
On line 28, you use = which is assignment instead of == for comparison. Your compiler likely generates a warning for this.
Thanks!
Topic archived. No new replies allowed.