以下是用于创建链表的结构的格式:
struct LetterFrequencyPair
{
char character;
int frequency;
struct LetterFrequencyPair* next;
};
/ ********************************************** ************************************** \
void createList()
{
char c;
int f;
struct LetterFrequencyPair* temp;
temp = malloc(sizeof(struct LetterFrequencyPair));
printf("Enter the Character: ");
scanf("%c", &c);
temp->character = c;
printf("Enter the frequency of the character: ");
scanf("%d", &f);
getchar();
temp->frequency = f;
temp->next = NULL;
if (root == NULL)
{
root = temp;
}
else
{
struct LetterFrequencyPair* p;
p = root;
while (p->next != NULL)
{
p = p->next;
}
p->next = temp;
}
printf("\n");
}
上面是我编写的用于创建链接列表的函数。
我的问题是如何修改此函数和结构以生成二叉树?
我知道我必须更改结构以具有指向左右孩子的指针,而不是下一个。但是当尝试将它们全部链接时,我会陷入困境,因为有两个不同的方向。我在下面粘贴了我尝试的修改内容:
struct LetterFrequencyPair
{
char character;
int frequency;
//Creating a pointer to point to the next child in the list
struct BinaryTreeNode* leftChild;
struct BinaryTreeNode* rightChild;
};
void createList()
{
char c;
int f;
struct LetterFrequencyPair* temp;
temp = malloc(sizeof(struct LetterFrequencyPair));
printf("Enter the Character: ");
scanf("%c", &c);
temp->character = c;
printf("Enter the frequency of the character: ");
scanf("%d", &f);
getchar();
temp->frequency = f;
temp->leftChild = NULL;
temp->rightChild = NULL;
if ((rootRight = NULL) && (rootLeft = NULL))
{
root = temp;
}
else
{
struct LetterFrequencyPair* p;
p = root;
while (p->leftChild != NULL)
{
p = p->leftChild;
}
p->leftChild = temp;
struct LetterFrequencyPair * p1;
p1 = root;
while (p1->rightChild != NULL)
{
p1 = p1 ->rightChild;
}
p1->rightChild = temp;
}
printf("\n");
}