用·c语言深度遍历和广度遍历实现二叉树深度的计算
时间: 2023-09-01 15:07:44 浏览: 155
以下是使用C语言实现二叉树深度遍历和广度遍历计算深度的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
//定义二叉树结构体
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
//创建二叉树
TreeNode* createTree() {
TreeNode *root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->val = 2;
root->left->left = NULL;
root->left->right = NULL;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 3;
root->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->left->val = 4;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->val = 5;
root->right->right->left = NULL;
root->right->right->right = NULL;
return root;
}
//深度优先搜索(DFS)实现二叉树深度计算
int maxDepthDFS(TreeNode* root) {
if (root == NULL) return 0;
int leftDepth = maxDepthDFS(root->left);
int rightDepth = maxDepthDFS(root->right);
return (leftDepth > rightDepth) ? (leftDepth + 1) : (rightDepth + 1);
}
//广度优先搜索(BFS)实现二叉树深度计算
int maxDepthBFS(TreeNode* root) {
if (root == NULL) return 0;
int depth = 0;
TreeNode *queue[100];
int front = 0, rear = 0;
queue[rear++] = root;
while (front != rear) {
int size = rear - front;
for (int i = 0; i < size; i++) {
TreeNode *node = queue[front++];
if (node->left) queue[rear++] = node->left;
if (node->right) queue[rear++] = node->right;
}
depth++;
}
return depth;
}
int main() {
TreeNode *root = createTree();
printf("深度优先搜索(DFS)计算二叉树深度:%d\n", maxDepthDFS(root));
printf("广度优先搜索(BFS)计算二叉树深度:%d\n", maxDepthBFS(root));
return 0;
}
```
这里使用了一个简单的二叉树作为示例,可以根据实际情况更改二叉树结构和节点值。其中,深度优先搜索(DFS)和广度优先搜索(BFS)分别实现了二叉树深度的计算。
阅读全文