1. 全局定义
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 100
typedef char Treetype;
typedef struct TreeNode {
Treetype data;
struct TreeNode *lchild;
struct TreeNode *rchild;
} TreeNode;
typedef TreeNode* ElemType;
typedef struct {
ElemType *data;
int front;
int rear;
} Queue;
typedef TreeNode* BiTree;
char str[] = "ABDH#K###E##CFI###G#J##";
int idx = 0;
2. 创建二叉树函数 createTree
void createTree(BiTree *T) {
Treetype ch = str[idx++];
if (ch == '#') {
*T = NULL;
} else {
*T = (BiTree)malloc(sizeof(TreeNode));
(*T)->data = ch;
createTree(&(*T)->lchild);
createTree(&(*T)->rchild);
}
}
功能:根据字符串 str 递归地创建二叉树。
str中取出一个字符,索引idx加 1。- 若字符为
#,表示该节点为空,将指针置为NULL。 - 若字符不为
#,为节点分配内存,存储字符,递归创建左子树和右子树。
3. 初始化队列函数 initQueue
Queue* initQueue() {
Queue *q = (Queue*)malloc(sizeof(Queue));
q->data = (ElemType*)malloc(sizeof(ElemType) * MAXSIZE);
q->front = 0;
q->rear = 0;
return q;
}
功能:为队列分配内存并初始化队头和队尾指针。
- 为队列结构体分配内存。
- 为队列的数据数组分配内存。
- 初始化队头和队尾指针为 0。
- 返回队列指针。
4. 释放队列内存函数 freeQueue
void freeQueue(Queue *Q) {
free(Q->data);
free(Q);
}
功能:释放队列所占用的内存。
- 释放队列的数据数组内存。
- 释放队列结构体本身的内存。
5. 判断队列是否为空函数 isEmpty
int isEmpty(Queue *Q) {
return Q->front == Q->rear;
}
6. 入队函数 enqueue
int enqueue(Queue *Q, ElemType e) {
if ((Q->rear + 1) % MAXSIZE == Q->front) {
return 0; // 队列满
}
Q->data[Q->rear] = e;
Q->rear = (Q->rear + 1) % MAXSIZE;
return 1;
}
功能:将元素 e 加入队列。
- 检查队列是否已满(队尾指针加 1 取模等于队头指针)。
- 若未满,将元素存入队尾位置。
- 队尾指针加 1 取模更新。
- 返回 1 表示入队成功。
7. 出队函数 dequeue
int dequeue(Queue *Q, ElemType *e) {
if (isEmpty(Q)) {
return 0;
}
*e = Q->data[Q->front];
Q->front = (Q->front + 1) % MAXSIZE;
return 1;
}
- 功能:从队列中取出元素。
- 步骤:
- 检查队列是否为空。
- 若不为空,取出队头元素存入
e指向的位置。 - 队头指针加 1 取模更新。
- 返回 1 表示出队成功。
8. 获取队列元素数量函数 queueSize
int queueSize(Queue *Q) {
return (Q->rear - Q->front + MAXSIZE) % MAXSIZE;
}
功能:计算队列中元素的数量。
原理:通过队尾指针减去队头指针加最大容量取模得到元素数量。
9. 释放树内存函数 freeTree
void freeTree(BiTree T) {
if (T) {
freeTree(T->lchild);
freeTree(T->rchild);
free(T);
}
}
- 功能:递归地释放二叉树所占用的内存。
- 步骤:
- 若节点不为空,先递归释放左子树。
- 再递归释放右子树。
- 最后释放当前节点的内存。
10. 计算树的最大深度函数 maxDepth
int maxDepth(TreeNode* root) {
if (root == NULL) {
return 0;
}
int depth = 0;
Queue *q = initQueue();
enqueue(q, root);
while (!isEmpty(q)) {
int count = queueSize(q);
while (count > 0) {
TreeNode* curr;
dequeue(q, &curr);
if (curr->lchild != NULL) {
enqueue(q, curr->lchild);
}
if (curr->rchild != NULL) {
enqueue(q, curr->rchild);
}
count--;
}
depth++;
}
freeQueue(q);
return depth;
}
功能:使用队列进行层序遍历,计算二叉树的最大深度。
- 若根节点为空,返回深度 0。
- 初始化队列,将根节点入队。
- 当队列不为空时,进行层序遍历:
- 记录当前层的节点数量
count。 - 依次取出当前层的节点,将其左右子节点入队。
- 当前层遍历完后,深度加 1。
- 释放队列内存,返回深度。
11. 主函数 main
int main() {
BiTree T;
createTree(&T);
printf("Tree depth: %d\n", maxDepth(T));
freeTree(T);
return 0;
}

1202

被折叠的 条评论
为什么被折叠?



