写一个C语言算法计算二叉树的深度
时间: 2024-05-06 16:16:43 浏览: 116
二叉树的深度可以通过递归的方式来计算。
首先,我们需要定义二叉树的结构体:
```c
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
```
然后,我们可以编写一个递归函数来计算二叉树的深度:
```c
int maxDepth(TreeNode* root) {
if (root == NULL) {
return 0;
}
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
return 1 + (leftDepth > rightDepth ? leftDepth : rightDepth);
}
```
该函数的实现思路如下:
- 如果当前节点为空,则返回深度为 0。
- 否则,分别递归计算左右子树的深度。
- 返回左右子树深度的最大值加上 1(表示当前节点的深度)。
完整代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
int maxDepth(TreeNode* root) {
if (root == NULL) {
return 0;
}
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
return 1 + (leftDepth > rightDepth ? leftDepth : rightDepth);
}
int main() {
// 构建一棵二叉树
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;
// 计算二叉树深度并输出结果
printf("The depth of the binary tree is: %d\n", maxDepth(root));
return 0;
}
```
输出:
```
The depth of the binary tree is: 3
```
阅读全文