C语言完成以下代码:给定一棵有根结点的二叉树,规定连接两个结点的每条边长度为1。定义树的深度(Depth)为树中各结点的最大层数,也称为树的高度(Height)。根结点处在第1层,深度为1。
时间: 2024-05-06 22:17:14 浏览: 75
二叉树的深度1
以下是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 + 1) : (rightDepth + 1);
}
}
/* 创建二叉树 */
struct TreeNode* createTree() {
int val;
scanf("%d", &val);
if (val == -1) {
return NULL;
} else {
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = val;
root->left = createTree();
root->right = createTree();
return root;
}
}
int main() {
struct TreeNode* root = createTree();
int depth = maxDepth(root);
printf("Depth of the tree: %d\n", depth);
return 0;
}
```
输入样例:
```
1 2 -1 -1 3 4 -1 -1 5 -1 -1
```
输出样例:
```
Depth of the tree: 3
```
阅读全文