树的孩子兄弟表示法: 左孩子有兄弟的二叉链表
结构:
typedef struct Node{
int data;
struct Node *child;//孩子域
struct NOde *brother;//兄弟域
}Node,*BiTree;
思想:
非递归思想:
先把根入队
1、此时计算出队长Len,
2、for循环len次-执行如下的运算:
将队头出队,将队头的孩子c和c的兄弟及
兄弟的兄弟直到没兄弟~ing全部依次入队。
此时树中的一层全部出队,树的下一层全部入队!
3、h++;
执行上三步,直到队列空!!
代码:
int MaxWide = 0;//记录最大宽度,即单层拥有的最多结点数,初始记为0
int height(BiTree T){
BiTree p = T;
if(!p){//树为空,高度为0
return 0;
}//end-if
InitQueue(Q);//建立空队列
EnQueue(Q,p);//根入队列
int H = 0;//记录层次数/高度
int len;//记录队长
while(!isEmptyQueue(Q)){//遍历队列
len = QueueLength(Q);//取当前队列长度,即当前层的结点数
if(len > MaxWide){
MaxWide = len;//记录最大结点数
}//end-if
for (int j = 1;j <= len;j++){
DeQueue(Q,p);//出队
if(p->child){//如果有孩子--入队
EnQueue(Q,p->child);
p = p->child;
while(p->brother){
//如果有兄弟,将所有的兄弟,兄弟的兄弟......都入队
EnQueue(Q,p->brother);
p = p->brother;
}//end-while
}//end-if
}//end-for
H++;//每结束for循环,当前层的结点全部出队,则高度加一
}//end-while
return H;
}//end-function
递归:
int Height(BiTree T){
if(!T) return 0;//end-if
else{
int hc,hs;
//hc表示第一子女树高;hs表示兄弟树高
hc = Height(T->child);
hs = Height(T->brother);
if(hc + 1 > hs) return hc + 1;//end-if
else return hs;//end-else
}//end-else
}//end-function