我有以下用于实现 BinarySearchTree 的代码。不知何故,它没有构建二叉树。任何人都可以帮助解决问题吗?
typedef struct BinarySearchTree
{
struct BinarySearchTree *left;
int nodeval;
struct BinarySearchTree *right;
}
BST;
BST *root=NULL;
void addrootnode(BST *,int );
void addnode(BST *,int );
void deletenode(int );
void printnodes();
main()
{
int nodeval;
char choice;
printf("\n r->rootnode \n a->add \n d->delete \n p->print \n e->exit\n");
while (1)
{
printf("\nEnter your choice:");
scanf("%c",&choice);
switch (choice)
{
case 'r':
printf("\nEnter the root node value to add: ");
scanf("%d",&nodeval);
addrootnode(root,nodeval);
break;
case 'a':
printf("\nEnter the node value to add: ");
scanf("%d",&nodeval);
addnode(root,nodeval);
break;
case 'd':
printf("\nEnter the node value to delete: ");
scanf("%d",&nodeval);
break;
case 'p':
//printf("\n");
printnodes(root);
break;
case 'e':
exit(0);
default:
break;
}
}
getchar();
}//end of main
//addrootnode
void addrootnode(BST *ptr,int num)
{
if(ptr==NULL)
{
ptr=(BST *) malloc(sizeof(BST));
ptr->left=NULL;
ptr->nodeval=num;
ptr->right=NULL;
root=ptr;
}
}
//add node
void addnode(BST *ptr,int num)
{
if(ptr==NULL)
{
ptr=(BST *) malloc(sizeof(BST));
ptr->left=NULL;
ptr->nodeval=num;
ptr->right=NULL;
}
else if(num < ptr->nodeval )
{
addnode(ptr->left,num);
}
else
{
addnode(ptr->right,num);
}
}
//delete functionality
void deletenode(int nodeval)
{
}
//print all nodes
void printnodes(BST *ptr)
{
if (ptr)
{
printnodes(ptr->left);
printf("%d\t",ptr->nodeval);
printnodes(ptr->right);
}
}