I have finally gotten all of my functions to work after testing the insert function and the swapSubTrees and printTree functions. Now I need to create a Binary Tree from a file and I get the file to open and read the first integer of the file but then my program crashes.
There is a ton of a code and I do not want to make a wall of code. I will post my important parts and if required will supply the rest of the code if asked for.
My function to swap and print are:
template<class elemType>
void bSearchTreeType<elemType>::printTree()
{
printTree(root);
}
template<class elemType>
void bSearchTreeType<elemType>::printTree(nodeType<elemType> *p)
{
if(p != NULL)
cout << p->info << endl;
printTree(p->lLink);
printTree(p->rLink);
}
template<class elemType>
void bSearchTreeType<elemType>::swapSubtrees(nodeType<elemType> * p)
{
if (p != NULL)
{
if (p->lLink != NULL && p->rLink != NULL)
{
nodeType<elemType> * temp = p->lLink;
p->lLink = p->rLink;
p->rLink = temp;
delete temp;
}
if (p->lLink != NULL && p->rLink == NULL)
{
swapSubtrees(p->lLink);
}
if (p->rLink != NULL && p->lLink == NULL)
{
swapSubtrees(p->rLink);
}
}
}
My main program is :
#include<iostream>
#include<fstream>
#include<cstdlib>
#include "binarySearchTree.h"
using namespace std;
int main()
{
bSearchTreeType<int>bt;
ifstream infile;
infile.open("binaryTree.txt");
if(!infile){
cout<<"File not found"<<endl;
}
int tree;
while(infile>> tree)
{
bt.insert(tree);
}
bt.swapSubtrees();
bt.printTree();
bt.swapSubtrees();
system("PAUSE");
return 0;
}
The program completely compiles and runs and starts to print the list starting with 12:
This is contents of binaryTree.txt:
12 23 56 45 78 89 98 25 36 65 54
I am a little confused as why it keeps crashing. Any thoughts?
The program was not stable when I manually built the list. After the last item was printed the program would hang. Now it hangs when trying to print. i think it is a problem with the function.
Much Appreciated
You’re deleting a pointer that was pointing to lLink…. that would mean you’re deleting the entire lLink and presumably trying to reaccess it somewhere else?
The way to handle this is to just set temp to null instead of deleting. But it doesn’t really matter since temp is a local variable inside of that block which goes out of scope right after temp is set to null.
One other potential area that is problematic in print:-
you need braces to encompass more than one statement in the body of an if statement…