思路:设置level变量记录层数,last变量记录该层最右结点,在层次遍历出队时,让队列的front指针与last对比,相等证明该层遍历完了,last=rear,同时level+1,直至遍历完成,即队列为空,此时level即为二叉树的高度。完整代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MaxSize 100
struct tree {
int data;
struct tree* left;
struct tree* right;
};
typedef struct queue{
struct tree* numQ[MaxSize];
int front;
int rear;
}Queue;
Queue Q;
void initilize() { //初始化队列
Q.front = -1;
Q.rear = -1;
}
struct tree* creatTree (struct tree* root) {
int value;
scanf("%d", &value);
if (value == -1)
return NULL;
root = (struct tree*)malloc(sizeof(struct tree));
root->data = value;
printf("请输入%d的左子树:", root->data);
root->left = creatTree(root->left);
printf("请输入%d的右子树:", root->