非递归采用层序遍历的思想,当遍历到某一层的最后一个元素时与last(初值为1,这里采用的队列为空的条件为Q.rear=Q.front=0)相等则高度加1,若其子树不为空则入队,最后入队的又为该层的最后一个元素。
递归则分别递归其左右子树,其中较大值加1即为树的高度。
//求二叉树的高度(非递归)
int high(BiTree T){
Queue Q;
InitQueue(Q);
int last=1,level=0;
EnQueue(Q,T);
BiTree p;
while(!isEmptyQueue(Q)){
DeQueue(Q,p);
if(p->lchild) EnQueue(Q,p->lchild);
if(p->rchild) EnQueue(Q,p->rchild);
if(Q.front==last){
level++;
last=Q.rear;
}
}
printf("该二叉树的高度为:%d\n",level);
return level;
}
//求二叉树的高度(递归)
int high_rescursion(BiTree T){
if(T){
int lhigh=high_rescursion(T->lchild);
int rhigh=high_rescursion(T->rchild);
if(lhigh>rhigh) return lhigh+1;
else return rhigh+1;
}
return 0;
}
// 另外一种非递归,Java版的
public static int depth_Non(BinTree T) {
// 非递归
Queue<BinTree> Q = new Queue<>(20); // 大小为20
BinTree p = null;
int deep = 0;
Q.EnQueue(T);
while (!Q.isEmpty()) {
// size标记一层的数量,当处理完这一层deep就加1
int size = Q.length();
while (size>0) {
p = Q.DeQueue();
if (p.left != null) Q.EnQueue(p.left);
if (p.right != null) Q.EnQueue(p.right);
size--;
}
deep++;
}
return deep;
}
本文介绍了两种计算二叉树高度的方法:非递归和递归。非递归方法使用队列进行层序遍历,递归方法通过左右子树的最大高度确定整棵树的高度。
3237

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



