修复heap_printf队列溢出问题

This commit is contained in:
Jdhggg 2025-05-23 18:54:44 +08:00
parent 1aafe0a833
commit b124a1b3f3

67
heap.c
View File

@ -58,46 +58,37 @@ void heap_push(heap *tree,int val)
void heap_print(heap* tree,int root) void heap_print(heap* tree,int root)
{ {
int queue[3] = {0}; if (tree->size <= 0) return;
int font = root;
int rear = font+1; int* queue = (int*)malloc(tree->size * sizeof(int));
int flog = 1; int front = 0;
printf("[%d]\n",tree->data[root]); int rear = 1;
while (flog < tree->size) int count = 1;
queue[0] = root;
printf("[%d]\n", tree->data[root]);
while (front < rear && count < tree->size)
{ {
int flog_r = 0,flog_l = 0; int level_size = rear - front;
for (int i = 0;i<2;i++) for (int i = 0; i < level_size && count < tree->size; i++)
{ {
switch (i) int current = queue[front++];
{ int left = heap_get_left(tree, current);
case 0: int right = heap_get_right(tree, current);
flog_l= heap_get_left(tree,queue[font]);
if (flog_l > tree->size) if (left < tree->size) {
{ printf("[%d]", tree->data[left]);
continue; queue[rear++] = left;
} count++;
queue[rear] = flog_l;
rear = (rear+1) % 3;
printf("[%d]",tree->data[flog_l]);
flog++;
break;
case 1:
flog_r = heap_get_right(tree,queue[font]);
if (flog_r > tree->size)
{
continue;
}
queue[rear] = flog_r;
rear = (rear+1) % 3;
printf("[%d]",tree->data[flog_r]);
flog++;
break;
default:
break;
}
} }
printf("\n"); if (right < tree->size) {
font = (font+1) % 3; printf("[%d]", tree->data[right]);
queue[rear++] = right;
count++;
}
}
printf("\n");
} }
free(queue);
} }