方法一:层次遍历
int btDept(BiTree T){
/*
初始化两个队列,分别用来存储不同层次的结点,例如:用Q1来存储根节点,则出队根结点的时候,
根节点的左右孩子存储在Q2
*/
initQueue(Q1);
initQueue(Q2);
BiTree p;
int level = 0; //表示树的深度
EnQueue(Q,T);
while((!isEmpty(Q1) || (!isEmpty(Q2))){ //当两个队列都不为空的时候,继续循环出队
if(level % 2 == 0){ //初始的时候,将根节点入队Q1,第二层节点入队Q2...
deQueue(Q1,p);
if(isEmpty(Q1)){ //当队列为空时,说明这一层的结点已经全部出队,将此层加入到计数中
level++;
}
if(p->lchild != NULL){ //入队左右孩子时,入队到另一个队列
enQueue(Q2,p->lchild);
}
if(p->rchild != NULL){
enQueue(Q2,p->rchild);
}
}
else{
deQueue(Q2,p);
if(isEmpty(Q2)){
level++;
}
if(p->lchild != NULL){
enQueue(Q1,p->lchild);
}
if(p->rchild != NULL){
enQueue(Q1,p->rchild);
}
}
}
return level;
}
方法二:利用后序遍历,当遍历到某一个结点时,其所有的祖先节点都在栈中,维持一个栈中的最大数,即树的最大深度
int postOrder(BiTree T){
InitStack(S);
BiTree p = T;
r = NULL; //r表示最近访问过的结点
int max = 0, count = 0;
while(p || !isEmpty(S)){
if(p){
push(S,p); //根节点以下所有的左子树都放进栈中
count++;
p = p->lchild;
}
else{
getPop(S,p);
if(p->rchild && p->rchild != r){
p = p->rchild;
}
else{
max = max>count? max:count;
pop(S,p);
r = p;
p = NULL;
}
}
}
return max;
}