У меня есть следующая программа на C, которая добавляет узлы в дерево, а затем пользователь может выбрать метод сортировки. Как я могу изменить программу таким образом, чтобы я мог добавить LChild и RChild к каждому узлу? Любая помощь высоко ценится, так как я совершенно новый для BST.
Writiong это потому что, видимо, мой пост в основном код
Код:
#include <stdio.h>
#include <stdlib.h>
struct treenode {
struct treenode *lchild;
struct treenode *rchild;
int data;
} *root = NULL;
void insertnode(struct treenode **pp,int d)
{
for( ;*pp; )
{
if (d < (*pp)->data) pp = &(*pp)->lchild;
else pp = &(*pp)->rchild;
}
*pp = malloc (sizeof **pp);
(*pp)->data = d;
(*pp)->lchild = NULL;
(*pp)->rchild = NULL;
}
void preorder(struct treenode *p)
{
if(p==NULL)
{
printf("\nThe list is empty");
return;
}
printf("%d,",p->data);
if (p->lchild) preorder(p->lchild);
if (p->rchild) preorder(p->rchild);
}
void postorder(struct treenode *p)
{
if(p==NULL)
{
printf("\nThe list is empty");
return;
}
if (p->lchild) preorder(p->lchild);
if (p->rchild) preorder(p->rchild);
printf("%d,",p->data);
}
void inorder(struct treenode *p)
{
if(p==NULL)
{
printf("\nThe list is empty");
return;
}
if (p->lchild) preorder(p->lchild);
printf("%d,",p->data);
if (p->rchild) preorder(p->rchild);
}
int main(void)
{
root=NULL;
int choice,data;
while(1)
{
printf("\nPress 1 for inserting a node in BST fashion: ");
printf("\nPress 2 for traversing the tree in preorder fashion :");
printf("\nPress 3 for traversing the tree in postorder fashion :");
printf("\nPress 4 for traversing the tree in inorder fashion :");
printf("\nPress 5 to exit :");
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1: printf("\nEnter the data to be inserted:");
scanf("%d",&data);
insertnode( &root,data);
break;
case 2: preorder(root);
break;
case 3: postorder(root);
break;
case 4: inorder(root);
break;
case 5: exit(0);
break;
default: printf("\nYou have entered an invalid choice. Please try again");
}
}
return 0;
}