来自二叉树的打印输出问题

时间:2019-02-04 22:37:24

标签: c linked-list binary-tree

我必须从文件country.txt中读取数据。该文件包含国家/地区名称及其ID,然后将它们插入到链表中(已排序的插入字母)。链接列表节点包含国家名称,国家ID和指向包含该国家城市的二叉树根的指针。我必须从其他文件(cities.txt)中插入城市。

我成功插入了国家,但是我无法插入城市。

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct CITY{
    char *name;
    struct CITY *left;
    struct CITY *right;
}nodeCity;

typedef struct COUNTRY{
    char *name;
    int id;
    struct CITY *root;
    struct COUNTRY *next;
}nodeCountry;

int listInsert(nodeCountry**, char*, int);
int printList(nodeCountry*);
nodeCity* findCity(nodeCountry*, int);
nodeCity* treeInsert(nodeCity*, char*);
int inorderPrint(nodeCity*);


int main()
{
nodeCountry *head;
int result, ID, k;
FILE *cities, *countries;
char buffer[1024];
nodeCity *root;

head = NULL;

countries = fopen("countries.txt", "r");

while(fscanf(countries, "%s %d", buffer, &ID) == 2)
    result = listInsert(&head, buffer, ID);

cities = fopen("cities.txt", "r");

while(fscanf(cities, "%s %d", buffer, &ID) == 2)
{
    root = findCity(head, ID);
    root = treeInsert(root, buffer);
}

//result = printList(head);
scanf("%d", &k);

root = findCity(head, k);

result = inorderPrint(root);

return 0;
}

int inorderPrint(nodeCity *root)
{
int result;
if(root == NULL)
return NULL;

result = inorderPrint(root->left);
printf("%s\n", root->name);
result = inorderPrint(root->right);

return 1;
}

nodeCity* treeInsert(nodeCity *root, char *buffer)
{
printf("K");
if(root == NULL){
    root = (nodeCity*)malloc(sizeof(nodeCity));
    root->name = strdup(buffer);
    root->left = NULL;
    root->right = NULL;
}

else if(strcmp(buffer, root->name) > 0)
    root->right = treeInsert(root->right, buffer);

else if(strcmp(buffer, root->name) < 0)
    root->left = treeInsert(root->left, buffer);

return root;
}

nodeCity* findCity(nodeCountry *head, int ID)
{
while(head->id != ID)
    head = head->next;

return head->root;
}

int listInsert(nodeCountry **head, char *buffer, int ID)
{
nodeCountry *current, *new_node;

if((*head) == NULL)
{
    (*head) =             
(nodeCountry*)malloc(sizeof(nodeCountry));
    (*head)->name = strdup(buffer);
    (*head)->id = ID;
    (*head)->root = NULL;
    (*head)->next = NULL;
    return 1;
}

if(strcmp(buffer, (*head)->name) < 0)
{
    new_node =         
(nodeCountry*)malloc(sizeof(nodeCountry));
    new_node->name = strdup(buffer);
    new_node->id = ID;
    new_node->root = NULL;
    new_node->next = (*head);
    (*head) = new_node;
    return 1;
}

current = (*head);

while(current->next != NULL && strcmp(buffer, current->next->name) > 0)
    current = current->next;

new_node = (nodeCountry*)malloc(sizeof(nodeCountry));
new_node->name = strdup(buffer);
new_node->id = ID;
new_node->next = current->next;
current->next = new_node;
new_node->root = NULL;

return 1;
}

int printList(nodeCountry *current)
{
while(current != NULL)
{
    printf("%s\n", current->name);
    current = current->next;
}

return 1;
}

0 个答案:

没有答案