Still can't find largest number in binary tree - c++

I still can't find the largest number in my tree, but now I am really not complicating it, I think it should work, there is no error, but it just won't show me in the console. Anyone got an idea? I am getting really frustrated.
Here is my entire code:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
template<class T>
class BinaryTree
{
struct Node
{
T data;
Node* lChildptr;
Node* rChildptr;
Node(T dataNew)
{
data = dataNew;
lChildptr = NULL;
rChildptr = NULL;
}
};
private:
Node* root;
void Insert(T newData, Node* &theRoot)
{
if(theRoot == NULL)
{
theRoot = new Node(newData);
return;
}
if(newData < theRoot->data)
Insert(newData, theRoot->lChildptr);
else
Insert(newData, theRoot->rChildptr);;
}
void PrintTree(Node* theRoot)
{
if(theRoot != NULL)
{
PrintTree(theRoot->lChildptr);
cout<< theRoot->data<<" \n";;
PrintTree(theRoot->rChildptr);
}
}
T Largest( Node* theRoot)
{
if ( root == NULL ){
cout<<"There is no tree";
return -1;
}
if (theRoot->rChildptr != NULL)
return Largest(theRoot->rChildptr);
else
return theRoot->data;
cout<<theRoot->data;
};
public:
BinaryTree()
{
root = NULL;
}
void AddItem(T newData)
{
Insert(newData, root);
}
void PrintTree()
{
PrintTree(root);
}
T Largest()
{
return Largest(root);
}
};
int main()
{
BinaryTree<int> *myBT = new BinaryTree<int>();
myBT->AddItem(2);
myBT->AddItem(5);
myBT->AddItem(1);
myBT->AddItem(10);
myBT->AddItem(15);
myBT->PrintTree();
myBT->Largest();
}
and here is the part that is supposed to find the largest number (the child that is far right down):
T Largest( Node* theRoot)
{
if ( root == NULL ){
cout<<"There is no tree";
return -1;
}
if (theRoot->rChildptr != NULL)
return Largest(theRoot->rChildptr);
else
return theRoot->data;
cout<<theRoot->data;
};

There are two problems in your code in Largest():
It looks like you wanted to execute two statements in the else clause, but you didn't use braces.
You wanted to execute the cout print after returning, which is impossible. Switch the order around.
So you should replace your fragment of code with this:
else {
cout << theRoot->data;
return theRoot->data;
}
Incidentally, don't let double semicolons (;;) stay in your code. It's harmless in most cases, but it's always bad style.

Here's a fixed and slightly cleaned-up version that works:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
template<class T>
class BinaryTree
{
struct Node
{
T data;
Node* lChildptr;
Node* rChildptr;
Node(T dataNew)
{
data = dataNew;
lChildptr = 0;
rChildptr = 0;
}
};
private:
Node* root;
void Insert(T newData, Node** theRoot)
{
if (*theRoot == 0)
{
*theRoot = new Node(newData);
}
else if (newData < (*theRoot)->data)
Insert(newData, &((*theRoot)->lChildptr));
else
Insert(newData, &((*theRoot)->rChildptr));
}
void PrintTree(Node* theRoot)
{
if (theRoot != 0)
{
PrintTree(theRoot->lChildptr);
cout << theRoot->data << " " << endl;
PrintTree(theRoot->rChildptr);
}
}
T Largest(Node* theRoot)
{
if (root == 0)
{
throw "There is no tree";
}
if (theRoot->rChildptr != 0)
return Largest(theRoot->rChildptr);
else
return theRoot->data;
}
public:
BinaryTree()
{
root = 0;
}
void AddItem(T newData)
{
Insert(newData, &root);
}
void PrintTree()
{
PrintTree(root);
}
T Largest()
{
return Largest(root);
}
};
int main()
{
BinaryTree<int> *myBT = new BinaryTree<int>();
cout << "The tree is empty. Trying to find the largest element." << endl;
try
{
cout << "Largest element: " << myBT->Largest() << endl;
}
catch (const char* e)
{
cout << "Exception caught: " << e << endl;
}
myBT->AddItem(15);
myBT->AddItem(2);
myBT->AddItem(5);
myBT->AddItem(1);
myBT->AddItem(10);
cout << "Tree:" << endl;
myBT->PrintTree();
cout << "Largest element: " << myBT->Largest() << endl;
}
Output:
The tree is empty. Trying to find the largest element.
Exception caught: There is no tree
Tree:
1
2
5
10
15
Largest element: 15

Related

Getting segmentation fault when trying to print binary tree nodes in C++ [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
What is a segmentation fault?
(18 answers)
Why dereferencing a null pointer is undefined behaviour?
(13 answers)
Closed 7 months ago.
I have an implementation of a binary tree using pointers. I am trying to print its nodes using preorder depth first traversal using recursion. When the program gets to right nodes it says segmentation fault. The problem is that I cannot find the error/mistake in the binary tree implementation. Program works when i use different btree implementation, so I assume the problem is in this btree implementation using pointers.
Below is my binary tree implementation
#include "../data-structures/trees/binary-tree-pointers/tree.h"
using namespace std;
void PrintTree(BinaryTree<int> tree, BinaryTree<int>::node node) {
cout << tree.Label(node) << endl;
if (tree.LeftChild(node) != tree.lambda) PrintTree(tree, tree.LeftChild(node));
if (tree.RightChild(node) != tree.lambda) PrintTree(tree, tree.RightChild(node));
}
int main() {
BinaryTree<int> tree;
BinaryTree<int>::node node;
tree.CreateRoot(1);
tree.CreateLeftChild(tree.Root(), 2);
tree.CreateRightChild(tree.Root(), 3);
node = tree.Root();
node = tree.LeftChild(node);
tree.CreateLeftChild(node, 4);
tree.CreateRightChild(node, 5);
node = tree.LeftChild(node);
tree.CreateLeftChild(node, 7);
node = tree.Root();
node = tree.RightChild(node);
tree.CreateRightChild(node, 8);
PrintTree(tree, tree.Root());
return 0;
}
Here is my binary tree implementation:
#include <iostream>
#include <cstdlib>
template <typename nodeType>
class BinaryTree {
private:
struct Tnode {
Tnode *parent, *left, *right;
nodeType label;
};
Tnode *B;
public:
typedef Tnode* node;
const node lambda = NULL;
void Del(node n) {
if (n->left != NULL) Del(n->left);
if (n->right != NULL) Del(n->right);
delete n;
}
void Prnt(node n) {
std::cout << n->label << " ";
if (n->left != NULL) Prnt(n->left);
if (n->right != NULL) Prnt(n->right);
}
BinaryTree() {
B = NULL;
}
BinaryTree(nodeType x) {
B = new Tnode;
B->parent = B->left = B->right = NULL;
B->label = x;
}
bool IsEmpty() {
return B == lambda;
}
nodeType Label(node n) {
if (n == lambda) {
std::cout << "That node doesn't exist!" << std::endl;
exit(EXIT_FAILURE);
}
return n->label;
}
node Root() {
return B;
}
node Parent(node n) {
if (n == lambda) {
std::cout << "That node doesn't exist!" << std::endl;
exit(EXIT_FAILURE);
}
return n->parent;
}
node LeftChild(node n) {
if (n == lambda) {
std::cout << "That node doesn't exist!" << std::endl;
exit(EXIT_FAILURE);
}
return n->left;
}
node RightChild(node n) {
if (n == lambda) {
std::cout << "That node doesn't exist!" << std::endl;
exit(EXIT_FAILURE);
}
return n->right;
}
void ChangeLabel(node n, nodeType x) {
if (n == lambda) {
std::cout << "That node doesn't exist!" << std::endl;
exit(EXIT_FAILURE);
}
n->label = x;
}
void CreateRoot(nodeType x) {
if (!this->IsEmpty()) {
std::cout << "Can't create root! Tree is not empty!" << std::endl;
exit(EXIT_FAILURE);
}
B = new Tnode;
B->parent = B->left = B->right = NULL;
B->label = x;
}
void CreateLeftChild(node n, nodeType x) {
if (n == lambda) {
std::cout << "That node doesn't exist!" << std::endl;
exit(EXIT_FAILURE);
}
if (n->left != lambda) {
std::cout << "Can't create left node! It already exists" << std::endl;
exit(EXIT_FAILURE);
}
Tnode *newNode = new Tnode;
newNode->left = newNode->right = NULL;
newNode->parent = n;
newNode->label = x;
n->left = newNode;
}
void CreateRightChild(node n, nodeType x) {
if (n == lambda) {
std::cout << "That node doesn't exist!" << std::endl;
exit(EXIT_FAILURE);
}
if (n->right != lambda) {
std::cout << "Can't create right node! It already exists" << std::endl;
exit(EXIT_FAILURE);
}
Tnode *newNode = new Tnode;
newNode->label = x;
newNode->left = newNode->right = NULL;
newNode->parent = n;
n->right = newNode;
}
void Delete(node n) {
if (n == lambda) {
std::cout << "That node doesn't exist!" << std::endl;
exit(EXIT_FAILURE);
}
if (n->parent != NULL) {
if (n->parent->left == n) n->parent->left = NULL;
else n->parent->right = NULL;
Del(n);
}
else {
Del(n);
B = NULL;
}
}
void Print() {
Prnt(B);
std::cout << std::endl;
}
~BinaryTree() {
if (B != lambda) Del(B);
}
};

Why isn't my function returning the count? (Binary Tree)

Everything in my program works perfectly, except it is not showing the count for the field. I tried to change some codes but it does not seem to display it in the output. It seems like a easy mistake or something obviously but I have no idea why it doesn't display it. Can someone help?
#include <iostream>
using namespace std;
template<class T>
class BinaryTree
{
struct Node
{
T data;
Node* leftChild;
Node* rightChild;
Node(T dataNew)
{
data = dataNew;
leftChild= NULL;
rightChild = NULL;
}
};
private:
Node* root;
void Add(T new_Data, Node* &the_Root)
{
if (the_Root == NULL)
{
the_Root = new Node(new_Data);
return;
}
if (new_Data < the_Root->data)
Add(new_Data, the_Root->leftChild);
else
Add(new_Data, the_Root->rightChild);
}
int countTree(Node* the_Root)
{
if (the_Root == NULL)
return 0;
else {
int count = 1;
count += countTree(the_Root->leftChild);
count += countTree(the_Root->rightChild);
return count;
}
}
void PrintTree(Node* the_Root)
{
if (the_Root != NULL)
{
cout << the_Root->data <<" ";
PrintTree(the_Root->leftChild);
PrintTree(the_Root->rightChild);
}
}
public:
BinaryTree()
{
root = NULL;
}
void AddItem(T new_Data)
{
Add(new_Data, root);
}
int countTree()
{
return countTree(root);
}
void PrintTree()
{
PrintTree(root);
}
};
int main()
{
BinaryTree<int> *myBT = new BinaryTree<int>();
myBT->AddItem(6);
myBT->AddItem(5);
myBT->AddItem(4);
myBT->AddItem(18);
myBT->AddItem(6);
myBT->PrintTree();
myBT->countTree();
}
The count won't be shown simply because you didn't write any code to show the count.
Try changing myBT->countTree(); to cout << myBT->countTree();, and you will see the count printed.
You aren't actually doing anything with the result of myBT->countTree(). Try printing it:
std::cout << myBT->countTree() << std::endl;

Basic Binary Tree Program c++

So I have been learning all about Binary Trees and decided to write a simple program to demonstrate to myself that I can implement my knowledge into working code. All I am trying to do with this code is add 4 numbers into a binary tree and output the numbers in order from least to greatest. Although, I did run into a problem with my code. When i run the code, Visual Studio breaks it at lines 29 and 59. I believe the problem has to do with the recursive function addLeaf but maybe its something else. Any advise, solutions, or input would be greatly appreciated.!
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
struct node
{
int data;
node* left;
node* right;
};
node* root = NULL;
node* createLeaf(int data)
{
node* n = new node;
n->data = data;
n->left = NULL;
n->right = NULL;
return n;
}
void addLeaf(int data)
{
node* curr = root;
//If tree is empty, create first node
if(root == NULL)
{
root = createLeaf(data);
}
//Left(Less than)
else if(data < curr->data)
{
//Check for curr->left
if(curr->left != NULL)
{
addLeaf(data);
}
else //Adds node to left if null
{
curr->left = createLeaf(data);
}
}
//Right(greater than)
else if(data > curr->data)
{
//Check for curr->right
if(curr->right != NULL)
{
addLeaf(data);
}
else //Adds node if right is Null
{
curr->right = createLeaf(data);
}
}
else
{
cout << "The data " << data << " has already been received\n";
}
}
void printTree(node* Ptr)
{
if(root != NULL)
{
if(Ptr->left != NULL)
{
printTree(Ptr->left);
}
cout << Ptr->data << " ";
if(Ptr->right != NULL)
{
printTree(Ptr->right);
}
cout << Ptr->data << " ";
}
else
{
cout << "The Tree is empty\n";
}
}
int main()
{
int data[4] = {1, 7, 5, 4};
node* Ptr = root;
for(int i = 0; i < 4; i++)
{
addLeaf(data[i]);
}
printTree(Ptr);
system("PAUSE");
return 0;
}
one problem I can spot:
void addLeaf(int data)
{
node* curr = root;
.....
//Check for curr->left
if(curr->left != NULL)
{
addLeaf(data);
}
your so-called recursion did nothing. It only keep on calling addLeaf function, and the function keep on checking if root's left is not null and in turn call the addLeaf again.
Refactor all your code. Don't use any global variable. Make sure you passed correct parameters (e.g. you should pass the next level node to addLeaf)
The addleaf function is going to run infinitely. You only keep adding to the root without any check.
You assign Ptr to root, but then using new, assign it to some new address in memory, which the root does not point to.
You have to pass Ptr by reference to addLeaf, otherwise changes will be made to its copy which is destroyed as addLeaf terminates.
printTree prints the current node value twice (a copy paste error?)
Here is the complete code :
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
struct node
{
int data;
node* left;
node* right;
};
node* root = NULL;
node* createLeaf(int data)
{
node* n = new node;
n->data = data;
n->left = NULL;
n->right = NULL;
return n;
}
void addLeaf(node* &curr, int data)
{
//If tree is empty, create first node
if(curr == NULL)
{
curr = createLeaf(data);
}
//Left(Less than)
else if(data < curr->data)
{
addLeaf (curr->left, data);
}
//Right(greater than)
else if(data > curr->data)
{
addLeaf(curr->right, data);
}
else
{
cout << "The data " << data << " has already been received\n";
}
}
void printTree(node* Ptr)
{
if(root != NULL)
{
if(Ptr->left != NULL)
{
printTree(Ptr->left);
}
cout << Ptr->data << " ";
if(Ptr->right != NULL)
{
printTree(Ptr->right);
}
}
else
{
cout << "The Tree is empty\n";
}
}
int main()
{
int data[4] = {1, 7, 5, 4};
for(int i = 0; i < 4; i++)
{
addLeaf(root, data[i]);
}
printTree(root);
system("PAUSE");
return 0;
}

Priority Queue that utilizes BST -- DeleteLargest doesn't work

I am creating a priority queue that utilizes a binary search tree for my Data Structures class. But when I attempt to output the queue I always get 0. I have looked over my DeleteLargest and Dequeue member function but I can't find the mistake
Test.cpp
#include <iostream>
#include "CTree.h"
#include "PriorityQueueBST.h"
using namespace std;
int main()
{
int num, input, output;
cout << "Enter number of elements: ";
cin >> num;
PriorityQueueBST p;
for (int x = 0; x < num; x++)
{
cout << "Enter number " << x + 1
<< " of " << num << ": ";
cin >> input;
p.Enqueue(input);
}
for (int y = 0; y < num; y++)
{
cout << "Outputting number " << y + 1
<< " of " << num << ": ";
if(p.IsEmpty())
{
break; //we are done (this is an error!)
}
output = p.Dequeue();
cout << output << endl;
}
system("pause");
return 0;
//CTree* tr = new CTree();
//
//for (int i = 0; i < 3; i++)
// tr->Add();
//tr->View();
//system("pause");
//return 0;
}
BST Declaration file
//#ifndef CTREE_H
//#define CTREE_H
//using namespace std;
struct TreeNode
{
int info;
TreeNode* leftLink;
TreeNode* rightLink;
};
class CTree
{
private:
void AddItem( TreeNode*&, TreeNode*);
void DisplayTree(TreeNode*);
void Retrieve(TreeNode*&, TreeNode*,bool&);
void Destroy(TreeNode*&);
public:
CTree();
~CTree();
void Add();
void View();
bool IsEmpty();
int DeleteLargest(TreeNode*&);
TreeNode *tree;
};
//#endif
BST Implementation file
#include <iostream>
#include <string>
using namespace std;
#include "CTree.h"
CTree::CTree()
{
tree = NULL;
}
CTree::~CTree()
{
Destroy(tree);
}
void CTree::Destroy(TreeNode*& tree)
{
if (tree != NULL)
{
Destroy(tree->leftLink);
Destroy(tree->rightLink);
delete tree;
}
}
bool CTree::IsEmpty()
{
if(tree == NULL)
{
return true;
}
else
{
return false;
}
}
void CTree::Add()
{
TreeNode* newPerson = new TreeNode();
/*cout << "Enter the person's name: ";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cin.getline(newPerson->name, 20);*/
/* cout << "Enter the person's contribution: ";
cin >> newPerson->info;*/
/*bool found = false;*/
newPerson->leftLink = NULL;
newPerson->rightLink = NULL;
/*Retrieve(tree, newPerson, found);
if (found)
cout << "info allready entered\n";
else*/
AddItem(tree, newPerson);
}
void CTree::View()
{
if (IsEmpty())
{
cout<<"The list is empy";
}
else
{
DisplayTree(tree);
}
};
void CTree::AddItem( TreeNode*& ptr, TreeNode* newPer )
{
if (ptr == NULL)
{
ptr = newPer;
}
else if ( newPer->info < ptr->info)
AddItem(ptr->leftLink, newPer);
else
AddItem(ptr->rightLink, newPer);
}
void CTree::DisplayTree(TreeNode* ptr)
{
if (ptr == NULL)
return;
DisplayTree(ptr->rightLink);
cout << ptr->info << endl; //cout<<ptr->name<<" "<<"$"<<ptr->info <<endl;
DisplayTree(ptr->leftLink);
}
void CTree::Retrieve(TreeNode*& ptr, TreeNode* newPer, bool& found)
{
{
if (ptr == NULL)
{
found = false; // item is not found.
}
else if ( newPer->info < ptr->info)
{
Retrieve(ptr->leftLink, newPer, found);
}
// Search left subtree.
else if (newPer->info > ptr->info)
{
Retrieve(ptr->rightLink, newPer, found);// Search right subtree.
}
else
{
//newPer.info = ptr->info; // item is found.
found = true;
}
}
}
int CTree::DeleteLargest(TreeNode*& tr)
{
int largest = 0;;
TreeNode* prev;
TreeNode* cur;
prev = NULL;
cur = tr;
if (tr == NULL)
{
cout << "The tree is empty"<<endl;
}
else if (tr->rightLink == NULL)
{
largest = tr->info;
}
else
{
prev = tr;
tr = tr->rightLink;
DeleteLargest(tr);
}
return largest;
}
Priority Queue Declaration
//#include <iostream>
//using namespace std;
//#include "SortedLinkedList.h"
#ifndef PRIORITYQUEUESLL__H
#define PRIORITYQUEUESLL__H
class PriorityQueueBST
{
public:
PriorityQueueBST();
~PriorityQueueBST();
void Enqueue(int);
int Dequeue();
bool IsEmpty();
private:
CTree* ourTree;
//sslNode* head;
};
#endif
Priority Queue Implementation
#include <iostream>
using namespace std;
#include "CTree.h"
#include "PriorityQueueBST.h"
PriorityQueueBST::PriorityQueueBST()
{
ourTree = new CTree();
//head = NULL;
}
PriorityQueueBST::~PriorityQueueBST()
{
}
void PriorityQueueBST::Enqueue(int dataToEnter)
{
ourTree->Add();
}
int PriorityQueueBST::Dequeue()
{
//check for empty??
return ourTree->DeleteLargest(ourTree->tree);
}
bool PriorityQueueBST::IsEmpty()
{
return ourTree->IsEmpty();
}
Your output is always 0 because in
int CTree::DeleteLargest(TreeNode*& tr)
{
int largest = 0;;
TreeNode* prev;
TreeNode* cur;
prev = NULL;
cur = tr;
if (tr == NULL)
{
cout << "The tree is empty"<<endl;
}
else if (tr->rightLink == NULL)
{
largest = tr->info;
}
else
{
prev = tr;
tr = tr->rightLink;
DeleteLargest(tr);
}
return largest;
}
you only set largest to something potentially != 0 if tr->rightlink is NULL. Otherwise you recur and set the largest variable local to another invocation of the function. That change is lost when the recursion goes up again, and in the topmost invocation, largest is still 0.
In the last line of the else branch, you should either
largest = DeleteLargest(tr);
or
return DeleteLargest(tr);
Another problem is that, despite its name, deleteLargest doesn't actually delete anything, so with the above, you would still always get the same value.

Error "System.AccessViolationException" show binary tree after cut visualc++

I have a problem with this Binary Search Tree.
After that i cut a leave, if I try to show the tree VisualStudio answer me this message
An unhandled exception of type 'System.AccessViolationException' occurred in ABR1.exe
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
It's more that 3 days that i try to understand could someone help me???
// ABR1.cpp : main project file.
#include "stdafx.h"
#include <iostream>
using namespace System;
using namespace std;
template <class T>
class ABR{
private:
struct Leaf{
T value;
struct Leaf *DX; //
struct Leaf *SX; //
};
Leaf *root;
public:
//constructors
ABR() { root = NULL; }
//destructor
//~ABR();
void appendLeaf(T);
bool cutLeaf(T);
bool isInTree(T) const;
Leaf* findLeaf(T) const;
void showTreeInOrder() const { showTreeInOrder(root); }
void showTreeInOrder(Leaf *) const;
void showTreePreOrder() const { showTreePreOrder(root); }
void showTreePreOrder(Leaf *) const;
};
template <class T>
void ABR<T>::appendLeaf(T newValue){
if (isInTree(newValue)){
cout << "The value is just present..." << endl;
return;
}
Leaf *newLeaf; // To point to a new leaf
Leaf *ptrLeaf; // To move in the tree
// Allocate the necessary memory
newLeaf = new Leaf; //generate the new leaf
newLeaf-> value = newValue;
newLeaf-> DX = NULL;
newLeaf-> SX = NULL;
if(!root) //if is the first leaf
root = newLeaf;
else{
ptrLeaf = root;
//cout<<ptrLeaf->value<<ptrLeaf->SX<<ptrLeaf->DX<<endl;
while (ptrLeaf != NULL){
//cout << ptrLeaf->value <<"\t";
if (ptrLeaf->value < newValue){
if (ptrLeaf->DX == NULL){
ptrLeaf->DX = newLeaf;
return;
}
else
ptrLeaf = ptrLeaf->DX;
}
else{
if(ptrLeaf->SX == NULL){
ptrLeaf->SX = newLeaf;
return;
}
else
ptrLeaf = ptrLeaf->SX;
}
}
}
}
template <class T>
bool ABR<T>::isInTree(T toFind) const{
Leaf *ptrLeaf;
ptrLeaf = root;
while (ptrLeaf){
if (ptrLeaf->value == toFind)
return true;
else{
if (ptrLeaf->value < toFind)
ptrLeaf = ptrLeaf->DX;
else
ptrLeaf = ptrLeaf->SX;
}
}
return false;
}
template <class T>
typename ABR<T>::Leaf * ABR<T>::findLeaf(T toFind) const
{
Leaf *ptr;
ptr = root;
while(ptr != NULL)
{
//cout << ptr->value << "#" << endl;
if (toFind == ptr->value){
//cout << "Trovato";
return ptr;
}
else if (ptr->value < toFind)
ptr = ptr->DX;
else
ptr = ptr->SX;
} cout << "Element don't find" << endl;
return NULL;
}
template <class T>
void ABR<T>::showTreeInOrder(Leaf *ptr) const
{
if(ptr != NULL)
{
showTreeInOrder(ptr->SX);
cout << ptr->value << endl;
showTreeInOrder(ptr->DX);
}
}
template <class T>
void ABR<T>::showTreePreOrder(Leaf *ptr) const
{
if(ptr != NULL)
{
showTreePreOrder(ptr->DX);
cout << ptr->value << endl;
showTreePreOrder(ptr->SX);
}
}
template <class T>
bool ABR<T>::cutLeaf(T toCut)
{
Leaf *Leafptr, *tempLeafptr;
Leafptr = findLeaf(toCut);
if (Leafptr == NULL)
{
cout << "The element is not present..." << endl;
return false;
}
else if (Leafptr->DX == NULL)
{
tempLeafptr = Leafptr;
Leafptr = Leafptr->SX;
delete tempLeafptr;
return true;
}
else if (Leafptr->SX == NULL)
{
tempLeafptr = Leafptr;
Leafptr = Leafptr->DX;
delete tempLeafptr;
return true;
}
else
{
tempLeafptr = Leafptr->DX;
while (tempLeafptr->SX)
tempLeafptr = tempLeafptr->SX;
tempLeafptr->DX = Leafptr->SX;
tempLeafptr = Leafptr;
Leafptr = Leafptr->DX;
delete tempLeafptr;
return true;
}
}
int main(){
ABR<int> albero;
for(int a = 0.0; a < 100.0; a+= 3)
albero.appendLeaf(a);
albero.appendLeaf(1000);
albero.appendLeaf(1001);
albero.showTreePreOrder();
int b = 75;
albero.cutLeaf(b);
albero.showTreePreOrder(); //ERROR
//albero.showTreeInOrder();//SAME ERROR
system("PAUSE");
return 0;
}
You're recursing in showTreePreOrder and encountering a stack overflow. Running it in the debugger told me this in under one minute.
EDIT:
Your problem is in this section of cutLeaf(). First, you're assuming Leafptr->SX isn't null and you're deleting it, but it is null for the last leaf. Second, when you delete the leaf you don't set its parent's DX pointer to null. Therefore, when you traverse the list, you traverse into leaves that have been freed.
else if (Leafptr->DX == NULL)
{
tempLeafptr = Leafptr;
Leafptr = Leafptr->SX;
delete tempLeafptr;
return true;
}
The same problems exist in the else clause.