Need some help here.
Why after I insert the node, it loop back to insert node again, and it not back to the menu.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
using namespace std;
struct place
{
string cityName;
place *left, *right;
};
string myStr;
void inorder(place *root)
{
if(root->left != NULL)
{
inorder(root->left);
}
if(root != NULL)
{
cout<<setw(5) << root->cityName;
}
if(root->right !=NULL)
{
inorder(root->right);
}
}
void preorder(place *root)
{
if (root != NULL)
cout<< setw(5) << root->cityName;
if(root->left != NULL)
preorder(root->left);
if(root->right !=NULL)
preorder(root->right);
}
void postorder(place *root)
{
if (root->left != NULL)
postorder(root->left);
if (root->right != NULL)
postorder(root->right);
if (root != NULL)
cout<< setw(5) << root->cityName;
}
place *Insert(place *root, place *p)
{
place *walker, *parent;
if(root == NULL)
root = p;
else
{
walker = root;
while(walker != NULL)
{
parent = walker;
if(p->cityName < walker->cityName)
walker = walker->left;
else
if(p->cityName > walker->cityName)
walker = walker->right;
else
{
cout << "VALUE ALREADY EXIST!" <<endl;
return(false);
}
}
if(p->cityName < parent->cityName)
parent->left = p;
else
parent->right = p;
}
return root;
}
place *Enter(place *rt)
{
place *pNew = new place;
pNew->left = NULL;
pNew->right = NULL;
cout << "Enter a city:" << endl;
cin >> pNew->cityName;
rt = Insert(rt, pNew);
return rt;
}
void bstMenu()
{
int choice;
place *root;
root = NULL;
do{
cout << "BST Menu " << endl;
cout << "-----------" << endl;
cout << "1. Insert nodes " << endl;
cout << "2. Inorder Traversal " << endl;
cout << "3. PreOrder Traversal " << endl;
cout << "4. PostOrder " << endl;
cout << "5. Quit " << endl;
cout << "0. Back to Menu " << endl;
cout << "Enter choice: " << endl;
getline(cin, myStr);
stringstream(myStr) >> choice;
cout << endl;
switch (choice){
case 1:
root = Enter(root);
break;
case 2:
inorder(root);
break;
case 3:
preorder(root);
break;
case 4:
postorder(root);
break;
case 5:
cout << "Bye Bye" << endl << endl;
exit(1);
break;
case 0:
cout << "Back to Main Menu" << endl << endl;
break;
default:
cout << "error" <<endl;
}
}while(choice !=0);
}
int _tmain(int argc, _TCHAR* argv[])
{
bstMenu();
return 0;
}