Reputation: 183
My instructor has a specific output requirement for the way that the Binary Tree should be printed. He wants the output to be like so:
root { left_subtree }-{ right_subtree }
i.e:
12 {18} --{24}
18 {6} --{14}
6 {NULL} --{NULL}
etc...
I did not realize this till today, and I was already excited that I got my program to work.
template<class elemType>
struct nodeType
{
elemType info;
nodeType<elemType> *lLink;
nodeType<elemType> *rLink;
};
template<class elemType>
void bSearchTreeType<elemType>::printPreOrder(nodeType<elemType> *root1)
{
if(root1 != NULL) {
cout<<root1->info<<" "<<"{"<<root1->lLink<<"}"<<endl;//this is where I get the errors
printPreOrder(root1->lLink);
printPreOrder(root1->rlink);
}
}
template <class elemType>void bSearchTreeType<elemType>::insert(const elemType& insertItem){
nodeType<elemType> *current; //pointer to traverse the tree
nodeType<elemType> *trailCurrent; //pointer behind current
nodeType<elemType> *newNode; //pointer to create the node
newNode = new nodeType<elemType>; newNode->info = insertItem;
newNode->lLink = NULL;
newNode->rLink = NULL;
if (root1 == NULL)
root1 = newNode;
else {
current = root1;
while (current != NULL)
{
trailCurrent = current;
if (current->info == insertItem)
{
cout << "The item to be inserted is already ";
cout << "in the tree -- duplicates are not allowed." << endl;
return;
}
else if (current->info > insertItem)
current = current->lLink;
else
current = current->rLink;
}//end while
if (trailCurrent->info >insertItem)
trailCurrent->lLink = newNode;
else
trailCurrent->rLink = newNode;
}
}
How would I get my function to print out the left subTree and the right subTree. Everytime I try something I get a segmentation fault or weird memory address are output.
I am looking for guidance and help, anything from pseudo code to how to do it would be awesome. I am just confused
EDITED: To include the insert function and what I do when I get the errors
Upvotes: 0
Views: 2304
Reputation: 20393
You may try something along these lines:
template<class elemType>
void bSearchTreeType<elemType>::printPreOrder(nodeType<elemType> *root) {
if( root ) {
cout << root->info << " " << endl;
cout << "{";
if( root->left ) {
cout << root->left->info;
}
else {
cout << "NULL";
}
cout << "} -- ";
cout << "{";
if( root->right ) {
cout << root->right->info;
}
else {
cout << "NULL";
}
cout << "}";
cout << endl;
printPreOrder( root->left );
printPreOrder( root->right );
}
}
Upvotes: 1