帮我用c++写一段求二叉树深度的代码
时间: 2024-04-30 15:23:03 浏览: 14
以下为使用C语言实现求二叉树深度的代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
int maxDepth(struct TreeNode* root) {
if (root == NULL) {
return 0;
} else {
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
return (leftDepth > rightDepth ? leftDepth : rightDepth) + 1;
}
}
int main() {
// 构造一个二叉树
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = 1;
struct TreeNode* node2 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node2->val = 2;
struct TreeNode* node3 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node3->val = 3;
struct TreeNode* node4 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node4->val = 4;
struct TreeNode* node5 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node5->val = 5;
root->left = node2;
root->right = node3;
node2->left = node4;
node2->right = NULL;
node3->left = NULL;
node3->right = node5;
node4->left = NULL;
node4->right = NULL;
node5->left = NULL;
node5->right = NULL;
// 求二叉树深度
int depth = maxDepth(root);
printf("The depth of the binary tree is: %d\n", depth);
// 释放内存
free(node5);
free(node4);
free(node3);
free(node2);
free(root);
return 0;
}
```
这里我们构造了一个二叉树,并使用`maxDepth`函数求出了其深度。其中,`maxDepth`函数采用递归的方式实现,对于每一个节点,我们分别计算其左子树和右子树的深度,并取两者中的较大值,最后加上1即为该节点所在子树的深度。如果该节点为空,则返回0。最终,整棵树的深度即为根节点的深度。