01 二叉树的BFS(广度、层次或水平遍历实现)【Binary Tree 二叉树】

本文介绍了二叉树的BFS遍历,包括两种实现方式:递归和使用队列。BFS遍历顺序为1-2-3-4-5。采用队列实现的方式更易理解。
摘要由CSDN通过智能技术生成

二叉树的遍历分为BFS和DFS两种大类
下面完整实现BFS遍历二叉树

 * 例如二叉树
 *      1
 *     / \
 *    2   3
 *   /\
 * 4  5

BFS遍历结果:1-2-3-4-5

具体的代码实现:

方法一、采用递归遍历的方法实现

// Recursive C program for level order traversal of Binary Tree
#include <stdio.h>
#include <stdlib.h>

/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
    int data;
    struct node* left, *right;
};

/* Function protoypes */
void printGivenLevel(struct node* root, int level);
int height(struct node* node);
struct node* newNode(int data);

/* Function to print level order traversal a tree
 * 方法一:
 * 方法二见05
 * */
void printLevelOrder(struct node* root)
{
    int h = height(root);
    int i;
    for (i=1; i<=h; i++)
        printGivenLevel(root, i);
}

/* Print nodes at a given level */
void printGivenLevel(struct node* root, i
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您解答这个问题。 首先,我们需要先定义二叉树的结构体: ```c typedef struct BinaryTree { int data; struct BinaryTree* left; struct BinaryTree* right; } BinaryTreeNode; ``` 接下来,我们可以先实现深度优先遍历(DFS)来计算二叉树的深度。具体实现方式可以使用递归或栈来实现。下面是使用递归的实现方式: ```c int maxDepth(BinaryTreeNode* root) { if (root == NULL) { // 如果当前节点为空,则返回0 return 0; } int leftDepth = maxDepth(root->left); // 递归遍历左子树 int rightDepth = maxDepth(root->right); // 递归遍历右子树 return fmax(leftDepth, rightDepth) + 1; // 返回左右子树深度的最大值 + 1(加1表示当前节点的深度) } ``` 接下来,我们可以实现广度优先遍历BFS)来计算二叉树的深度。具体实现方式可以使用队列来实现。下面是使用队列的实现方式: ```c int maxDepth(BinaryTreeNode* root) { if (root == NULL) { // 如果当前节点为空,则返回0 return 0; } int depth = 0; Queue* queue = createQueue(); // 创建队列 enqueue(queue, root); // 根节点入队 while (!isEmpty(queue)) { // 队列不为空时 int size = getSize(queue); // 获取队列大小 for (int i = 0; i < size; i++) { BinaryTreeNode* node = dequeue(queue); // 出队 if (node->left != NULL) { enqueue(queue, node->left); // 左子节点入队 } if (node->right != NULL) { enqueue(queue, node->right); // 右子节点入队 } } depth++; // 遍历完一层,深度+1 } return depth; } ``` 以上就是使用 C 语言实现二叉树深度计算的方法,希望能对您有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值