编写函数int getDepth(BiTNode *T),计算二叉树T的深度,并给出完整代码
时间: 2024-01-22 08:17:18 浏览: 25
以下是计算二叉树深度的完整代码,其中getDepth函数返回二叉树的深度:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct BiTNode {
int data;
struct BiTNode *lchild, *rchild;
} BiTNode, *BiTree;
int getDepth(BiTree T);
int main() {
// 构造二叉树
BiTree T = (BiTree) malloc(sizeof(BiTNode));
T->data = 1;
T->lchild = (BiTree) malloc(sizeof(BiTNode));
T->lchild->data = 2;
T->rchild = (BiTree) malloc(sizeof(BiTNode));
T->rchild->data = 3;
T->lchild->lchild = (BiTree) malloc(sizeof(BiTNode));
T->lchild->lchild->data = 4;
T->lchild->rchild = (BiTree) malloc(sizeof(BiTNode));
T->lchild->rchild->data = 5;
printf("二叉树的深度为:%d\n", getDepth(T));
return 0;
}
int getDepth(BiTree T) {
if (T == NULL) {
return 0;
} else {
int leftDepth = getDepth(T->lchild);
int rightDepth = getDepth(T->rchild);
return (leftDepth > rightDepth) ? (leftDepth + 1) : (rightDepth + 1);
}
}
```
在上面的代码中,我们使用了递归的思想来计算二叉树的深度。如果当前节点为空,则返回0;否则,分别计算左子树和右子树的深度,并取较大值加1作为当前节点的深度。最终的二叉树深度即为根节点的深度。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)