【问题标题】:BFS Traversal of a Binary Tree in CC中二叉树的BFS遍历
【发布时间】:2022-01-02 16:56:41
【问题描述】:

虽然我知道在其他语言中存在用于 BFS 遍历的更简洁更高效的程序,但在 c 中它有点冗长
我在 leetcode 上发现了一些非常冗长和复杂的程序,作为初学者,这些程序有点难以理解,虽然我理解了它背后的基本概念,但我在这里找到了一个更简单、更清晰的代码 sanfoundry 但由于某种原因它不起作用?如果有人能帮我解决这个问题,我将不胜感激:)

#include <stdio.h>
#include <stdlib.h>
 
struct btnode
{ 
    int value; 
    struct btnode *left, *right; 
}; 
typedef struct btnode node;
 
/* function declarations */
void insert(node *, node *);
void bfs_traverse(node *);
 
/*global declarations */
node *root = NULL;
int val, front = 0, rear = -1, i;
int queue[20];
 
void main() 
{ 
    node *new = NULL ; 
    int num = 1; 
    printf("Enter the elements of the tree(enter 0 to exit)\n"); 
    while (1) 
    {     
        scanf("%d",  &num); 
        if (num  ==  0) 
            break; 
        new = malloc(sizeof(node)); 
        new->left = new->right = NULL; 
        new->value = num; 
        if (root == NULL) 
            root = new; 
        else 
        { 
            insert(new, root); 
        } 
    }
    printf("elements in a tree in inorder are\n"); 
    queue[++rear] = root->value;
    bfs_traverse(root);
    for (i = 0;i <= rear;i++)
        printf("%d -> ", queue[i]);
    printf("%d\n", root->right->right->right->value);
}
 
/* inserting nodes of a tree */
void insert(node * new , node *root) 
{ 
    if (new->value>root->value) 
    {     
        if (root->right == NULL) 
            root->right = new; 
        else 
            insert (new, root->right); 
    } 
    if (new->value < root->value) 
    {     
        if (root->left  ==  NULL) 
            root->left = new; 
        else 
            insert (new, root->left); 
    }     
}
 
/* displaying elements using BFS traversal */
void bfs_traverse(node *root)
{
    val = root->value;
    if ((front <= rear)&&(root->value == queue[front]))
    {
        if (root->left != NULL)
            queue[++rear] = root->left->value;
        if (root->right != NULL || root->right  ==  NULL)
            queue[++rear] = root->right->value;
        front++;
    }
    if (root->left != NULL)
    {
        bfs_traverse(root->left);
    }
    if (root->right != NULL)
    {
        bfs_traverse(root->right);
    }
}

【问题讨论】:

  • 为什么给出的答案没有反馈?

标签: c binary-tree breadth-first-search traversal


【解决方案1】:

我建议实现btnode * 类型的队列

btnode *queue[20]; // I assume 20 is enought for what you need
...
void bfs_traverse(node *root) {
    val = root->val; 
    if (front <= rear)
    {
        if (root->left != NULL)
            queue[++rear] = root->left;
        if (root->right != NULL)
            queue[++rear] = root->right;
        bfs_traverse(queue[front++]);
        
    }
    
}

但是,我宁愿使用 while 来实现它。它比递归函数干净得多。我会为 DFS 使用递归

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多