用C语言实现二叉链表树 树的初始化 清空树 销毁树 求树的深度 返回根结点数值 创建树 操作
时间: 2024-06-13 12:09:47 浏览: 3
以下是用C语言实现二叉链表树的相关操作:
1. 树的初始化
```c
typedef struct BiTNode {
int data;
struct BiTNode *lchild, *rchild;
} BiTNode, *BiTree;
void InitTree(BiTree *T) {
*T = NULL;
}
```
2. 清空树
```c
void ClearTree(BiTree *T) {
if (*T) {
if ((*T)->lchild) {
ClearTree(&((*T)->lchild));
}
if ((*T)->rchild) {
ClearTree(&((*T)->rchild));
}
free(*T);
*T = NULL;
}
}
```
3. 销毁树
```c
void DestroyTree(BiTree *T) {
ClearTree(T);
}
```
4. 求树的深度
```c
int TreeDepth(BiTree T) {
if (!T) {
return 0;
}
int ldepth = TreeDepth(T->lchild);
int rdepth = TreeDepth(T->rchild);
return (ldepth > rdepth ? ldepth : rdepth) + 1;
}
```
5. 返回根结点数值
```c
int Root(BiTree T) {
if (T) {
return T->data;
}
return -1;
}
```
6. 创建树
```c
void CreateTree(BiTree *T) {
int data;
scanf("%d", &data);
if (data == -1) {
*T = NULL;
} else {
*T = (BiTree)malloc(sizeof(BiTNode));
(*T)->data = data;
CreateTree(&((*T)->lchild));
CreateTree(&((*T)->rchild));
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)