繁体   English   中英

树:使用队列进行层级顺序遍历

[英]Tree: Level order Traversal using queue

我编写了使用队列遍历树的代码,但是下面的出队函数会产生错误, head = p->next有问题吗? 我不知道为什么这部分是错误的。

void Levelorder(void) {
node *tmp, *p;


if (root == NULL) return;

tmp = root;
printf("The level order is :\n");

while (tmp != NULL) {

    printf("%d, ", tmp->data);
    if (tmp->left) {
        enqueue(tmp->left);
    }
    if (tmp->right) {
        enqueue(tmp->right);
    }
    tmp = dequeue();
}

return;
}

void enqueue(node *p) {
if (head == NULL) {
    head = p;
}
else {
    tail->next = p;
}
tail = p;
p->next = NULL;
tail->next = NULL;

return;
}

node* dequeue(void) {
node *p;
p = head;
head = p->next;


if (head == NULL) {
    tail == NULL;
}

return p;
}

while循环的条件是:

while (tmp != NULL) {

因此,只有当dequeue返回NULL时,它才会终止:

    tmp = dequeue();

但是,当查看出队的实现时,这不会发生:

node* dequeue(void) {
    node *p;
    p = head;

在这里, p被取消引用:

    head = p->next;

    if (head == NULL) {
        tail == NULL;
    }

在这里, p返回:

    return p;
}

要返回NULL指针并退出while循环,此处p必须为NULL 但是然后,将使用head = p->next;取消head = p->next; NULL指针的引用head = p->next; 之前,这将导致分段错误(就C语言而言为UB)。

您应该在出队函数的开头检查head是否为NULL指针,并在这种情况下返回NULL:

node* dequeue(void) {
    node *p;
    if (!head)
         return NULL;

...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM