【发布时间】:2018-06-13 12:27:18
【问题描述】:
创建二叉树并不重要。我可以看到 LevelOrder 的打印结果,但它一直出现错误。如何在最小化更改的同时修复更改?我需要快点:( 我认为 print 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;
}
【问题讨论】:
-
您的要求并不完全清楚。哪些步骤有效,哪个步骤有问题?
-
当我编译你的代码时,我从 DELETE 的返回类型中得到错误。您试图返回一个指针,并使用 DELETE 的返回值作为指针,但 DELETE 将其转换为 int。我不是说这就是问题,但这是一个问题。
标签: c data-structures binary-tree tree-traversal