Обратный порядок на уровне двоичного дерева с использованием двойного указателя - PullRequest
0 голосов
/ 13 июня 2018

Создание двоичного дерева не имеет значения.Я вижу распечатанный результат LevelOrder, но он продолжает выдавать ошибку.Как я могу исправить изменения, минимизируя их?Мне нужно поторопиться :( Я думаю, что печать DELETE () является проблемой. Я пробовал много вещей, но не могу это исправить. Я должен использовать двойной указатель, тип структуры узла и очередь.

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

struct node **queue;
int front = 0, rear = -1, nodeCnt = 0;

struct node {
    struct node *llink;
    int data;
    struct node *rlink;
};

struct node *binaryTree(int a[], int left, int right) { //Creating Tree
    int mid;
    struct node *p = NULL;
    if (left <= right) {
        mid = (left + right) / 2;
        p = (struct node *)malloc(sizeof(struct node));
        nodeCnt++;
        printf("%d\n", a[mid]);
        p->data = a[mid];
        p->llink = binaryTree(a, left, mid - 1);
        p->rlink = binaryTree(a, mid + 1, right);
    }

    return p;
}

int ADD(struct node *data) { //Queue Add function
    if (rear == nodeCnt) {
        printf("Queue is full!\n");
        return -1;
    }

    queue[++rear] = data;
    return 0;
}

int DELETE() { //Queue Delete function
    struct node *node = NULL;
    if (front > rear) {
        printf("Queue is empty!");
        return -1;
    }

    node = queue[front++];
    return node;
}

int LevelOrder(struct node *str) { //Level order traversal function
    struct node *p = NULL; 
    if (str != NULL) {  
        ADD(str); //call ADD()
        while (1) {
            p = DELETE();
            if (str == NULL)
                break;
            printf("%d  ", p->data); //I think here and under this code is the problem
            if (p->llink != NULL)
                ADD(p->llink);
            if (p->rlink != NULL)
                ADD(p->rlink);
        }
    }
}

int main() {
    int a[] = { 3, 5, 7, 10, 15, 17, 20, 25, 28, 31, 33, 35 };
    struct node *root;
    int n = sizeof(a) / sizeof(int);
    int i;

    root = binaryTree(a, 0, n - 1); //call binaryTree function

    printf("\n");
    printf("\n");

    queue = (struct node **)malloc(sizeof(struct node *) *nodeCnt);
    //define queue with struct node type double pointer

    LevelOrder(root);


    return 0;
}

1 Ответ

0 голосов
/ 13 июня 2018

Было 2 проблемы:

  1. в LevelOrder функции вы неправильно использовали (str==NULL) вместо (p == NULL)

  2. невернотип возврата для DELETE()

Ниже приведен рабочий код:

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

struct node **queue;
int front = 0, rear = -1, nodeCnt = 0;

struct node
{
  struct node *llink;
  int data;
  struct node *rlink;
};

struct node *
binaryTree (int a[], int left, int right)
{               //Creating Tree
  int mid;
  struct node *p = NULL;
  if (left <= right)
    {
      mid = (left + right) / 2;
      p = (struct node *) malloc (sizeof (struct node));
      nodeCnt++;
      printf ("%d\n", a[mid]);
      p->data = a[mid];
      p->llink = binaryTree (a, left, mid - 1);
      p->rlink = binaryTree (a, mid + 1, right);
    }

  return p;
}

int
ADD (struct node *data)
{               //Queue Add function
  if (rear == nodeCnt)
    {
      printf ("Queue is full!\n");
      return -1;
    }

  queue[++rear] = data;
  return 0;
}

struct node *
DELETE ()
{               //Queue Delete function
  struct node *node = NULL;
  if (front > rear)
    {
      printf ("Queue is empty!");
      return NULL;
    }

  node = queue[front++];
  return node;
}

void
LevelOrder (struct node *str)
{               //Level order traversal function
  struct node *p = NULL;
  if (str != NULL)
    {
      ADD (str);        //call ADD()
      while (1)
    {
      p = DELETE ();
      if (p == NULL)
        break;
      printf ("%d  ", p->data); //I think here and under this code is the problem
      if (p->llink != NULL)
        ADD (p->llink);
      if (p->rlink != NULL)
        ADD (p->rlink);
    }
    }
}

int
main ()
{
  int a[] = { 3, 5, 7, 10, 15, 17, 20, 25, 28, 31, 33, 35 };
  struct node *root;
  int n = sizeof (a) / sizeof (int);
  int i;

  root = binaryTree (a, 0, n - 1);  //call binaryTree function

  printf ("\n");
  printf ("\n");

  queue = (struct node **) malloc (sizeof (struct node *) * nodeCnt);
  //define queue with struct node type double pointer

  LevelOrder (root);


  return 0;
}

Вывод:

17
7
3
5
10
15
28
20
25
33
31
35


17  7  28  3  10  20  33  5  15  25  31  35  Queue is empty!

Также необходимо полностьюудалить двоичное дерево.Вот функция удаления полного двоичного дерева:

void
deletetree (struct node *root)
{
  if (root == NULL)
    return;


  deletetree (root->llink);
  deletetree (root->rlink);

  printf ("\n Deleting node: %d", root->data);
  free (root);
  root = NULL;
}

В конце основной функции необходимо добавить:

  deletetree (root);
  free (queue);
...