预备的
#include<iostream>
#include<stdlib.h>
#include<queue>
#include<stack>
#include <cstdlib>//随机数头文件
#include <ctime>
#define null NULL
using namespace std;
typedef struct BiTreeNode {
//二叉树
int data;
struct BiTreeNode * lchild, *rchild;
} BiTreeNode,*BiTree;
函数
void Layer_high(BiTree t) {
if(!t) cout<<"0";
queue<BiTree> q;
BiTree temp;
int z;
if(q.empty()) cout<<"empty"<<endl;
int LastLayerSize=1;
int total=0;//总计数指针,包含当前层和下一层的总节点
int high=0;//树的高度
int count=0;//出队的个数指针
q.push(t);
total++;
while(!q.empty()) {
temp=q.front();
q.pop();
count++;
if(temp->rchild!=NULL) {
total++;
cout<<temp->data<<"->"<<temp->rchild->data<<endl;
q.push(temp->rchild);
}
if(temp->lchild!=NULL) {
total++;
cout<<temp->data<<"->"<<temp->lchild->data<<endl;
q.push(temp->lchild);
}
if(count==LastLayerSize) {
cout<<"this layer has nodes :"<<LastLayerSize<<endl;
high++;
//将z看作临时变量,目的是将让减去上一层的节点数和为当前层的节点数赋值
z=total;
total=total-LastLayerSize;
LastLayerSize=z-count;
count=0;
}
}
cout<<high;
}
主测试函数
int main() {
BiTreeNode a,b,c,d,e,f,g; //简单的测试数据
a.data=1;
b.data=2;
c.data=3;
d.data=4;
e.data=5;
f.data=6;
g.data=7;
a.lchild=&b;
a.rchild=&g;
b.lchild=&c;
b.rchild=NULL;
c.lchild=&d;
c.rchild=&e;
d.lchild=NULL;
d.rchild=NULL;
e.lchild=NULL;
e.rchild=&f;
f.lchild=NULL;
f.rchild=NULL;
g.lchild=NULL;
g.rchild=NULL;
BiTree t=&a;
Layer_high(t);
return 0;
}