ALL I want to do is making binary search tree, inputting there from users, and then print out data in each node one by one according to the user's selection (whether he choose to print the data in the right node of the current node or the left). So I only define three functions: prompt()
, inputData()
and printOneNode()
.
As you can see, I place the prompt()
function in an infinite while
loop and continuously prompt the user for selection, until he chooses to exit.
I have also made some comments in the source code for improvement of my code.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct BSTnode{
struct BSTnode* leftchild;
struct BSTnode* rightchild;
char data[20];
}BSTnode;
void prompt();
void inputData();
void printOneNode();
BSTnode firstNode;
BSTnode* MyNode=&firstNode; //I don't know if there is another better way to initialize the first node
int main()
{
//BSTnode* MyNode=malloc(sizeof(BSTnode)); //Can't initialize it in the main function , or it won't be accessible in another function
MyNode->leftchild=NULL;
MyNode->rightchild=NULL;
strcpy(MyNode->data,"");
while(1)
prompt();
return 0;
}
void prompt(){
int i=0;
printf("Please select:\n");
printf("1.input a data\n2.print only one data\n3.Exit\n");
scanf("%d",&i);
switch(i){
case 1:
inputData();
break;
case 2:
printOneNode();
break;
case 3:
exit(0);
default:
printf("Please input a valid number!(1-3)");
}
}
void inputData(){
char data[20]={0};
printf("Input your data here(character only / less than 19 characters!): ");
scanf("%s",data);
BSTnode** ptr=&MyNode;
while(1){
if(strcmp(data,(*ptr)->data)){
if((*ptr)->rightchild!=NULL){
ptr=&((*ptr)->rightchild);
continue;
}
else{
(*ptr)->rightchild=malloc(sizeof(BSTnode));
ptr=&((*ptr)->rightchild);
(*ptr)->rightchild=NULL;
(*ptr)->leftchild=NULL;
strcpy((*ptr)->data,data);
break;
}
}
else{
if((*ptr)->leftchild!=NULL){
ptr=&((*ptr)->leftchild);
continue;
}
else{
(*ptr)->leftchild=malloc(sizeof(BSTnode));
ptr=&((*ptr)->leftchild);
(*ptr)->leftchild=NULL;
(*ptr)->rightchild=NULL;
strcpy((*ptr)->data,data);
break;
}
}
}
printf(" Your data have been input successfully!\n");
return;
}
void printOneNode(){
BSTnode** ptr=&MyNode;
printf("The first node is%s\n",(*ptr)->data);
while(1){
printf("Select which side of node do you want to print now(l/r)?(q for quit) ");
char a;
getchar(); //have to use getchar() to clear the buffer of stdin,
// or the variable 'a' will automatically get a newline character.
//I guess there might be some function to help improve
scanf("%c",&a);
switch(a){
case 'l':
{
if((*ptr)->leftchild!=NULL){
ptr=&((*ptr)->leftchild);
printf("\t%s\n",(*ptr)->data);
}
else
printf("There is no more leftchild");
break;
}
case 'r':
{
if((*ptr)->rightchild!=NULL){
ptr=&((*ptr)->rightchild);
printf("\t%s\n",(*ptr)->data);
}
else
printf("There is no more rightchild!");
break;
}
case 'q':
return;
default:
return;
}
}
}