为什么创建二叉树用*T,求二叉树的深度用T?
时间: 2024-05-26 18:03:52 浏览: 9
在 C 语言中,使用指针来表示数据结构是比较方便的。因此,我们通常用*T来表示一个二叉树节点的指针。同时,我们也可以用T来表示整个二叉树的根节点的指针。
当我们求一棵二叉树的深度时,我们需要遍历整棵树,并且递归地向下计算每个子树的深度。由于二叉树的每个节点都有左右两个子节点,因此我们需要递归地访问左子树和右子树。为了方便表示,我们通常将这个递归函数的参数定义为一个指向当前节点的指针 T。
因此,我们使用*T来表示一个二叉树节点的指针,用T来表示整个二叉树的根节点的指针,以及在求二叉树深度时作为递归函数的参数。
相关问题
为什么创建二叉树时递归函数的参数用*T,而求二叉树深度时递归函数的参数为T?
这是因为创建二叉树时需要不断地创建新节点,递归函数需要对节点进行修改和操作,因此需要传递二叉树的指针(即二级指针),以便在递归函数中对节点进行修改。而求二叉树深度时,递归函数只需要遍历节点,不需要修改节点,所以只需要传递二叉树的指针即可,不需要传递二级指针。因此,在创建二叉树时递归函数的参数为*T,而求二叉树深度时递归函数的参数为T。
用c语言 编写函数bool isCompleteTree(BiTNode *T),判断T是否为完全二叉树
以下是用C语言编写的判断二叉树是否为完全二叉树的函数:
```c
#include <stdbool.h>
typedef struct BiTNode {
int data;
struct BiTNode *lchild, *rchild;
} BiTNode, *BiTree;
// 获取二叉树的深度
int getDepth(BiTree T) {
if (T == NULL) {
return 0;
} else {
int leftDepth = getDepth(T->lchild);
int rightDepth = getDepth(T->rchild);
return 1 + (leftDepth > rightDepth ? leftDepth : rightDepth);
}
}
bool isCompleteTree(BiTree T) {
if (T == NULL) { // 空树也是完全二叉树
return true;
}
int depth = getDepth(T);
int level = 1;
while (T) {
if (T->lchild == NULL && T->rchild != NULL) { // 左子树为空,右子树不为空,不是完全二叉树
return false;
}
if (level < depth - 1) { // 不到最后一层时,必须左右子树都存在
if (T->lchild == NULL || T->rchild == NULL) {
return false;
}
} else if (level == depth - 1) { // 如果是最后一层,那么只要左子树存在,右子树可以为空
if (T->lchild == NULL) {
return false;
}
if (T->rchild != NULL) {
return false;
}
} else { // 如果level > depth - 1,那么不可能存在非空节点
if (T->lchild != NULL || T->rchild != NULL) {
return false;
}
}
level++;
if (T->lchild != NULL) {
T = T->lchild;
} else {
T = T->rchild;
}
}
return true;
}
```
该函数的基本思路是:先获取二叉树的深度,然后从根节点开始逐层判断,如果左子树为空,右子树不为空,则不是完全二叉树;如果不到最后一层,那么左右子树都必须存在;如果是最后一层,那么只要左子树存在,右子树可以为空;如果超过了最后一层,那么不可能存在非空节点。
相关推荐
![](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)