非递归算法实现二叉树高度

思路:

嘻嘻,请读者自己手动模拟。博主这里不知道怎么用语言说。

拓展:

算法思路适用于

(1)每层的结点个数

(2)树的最大宽度

(3)节点位于某一层

int height(BiTree T){

if(T==null)
    return 0;
int front=-1, rear=-1;//front 出队指针   rear  入队指针
int last = 0, level=0;//last 每一层的最右指针(front==last时候一层遍历结束  level++)
BiTree Q[Maxsize];//模拟队列
Q[++rear] = T;
BiTree p;
while(front<rear){
    p = Q[++front];//开始出队   因为front要赶到lash  实现level++
    if(p->lchild)
        Q[++rear] = p->lchild;
    if(p->rchild)
        Q[++rear] = p->rchild;
    if(front==last){
        level++;
        last=rear;//last指向下层节点
    }
}

}


您可能感兴趣的

猜你喜欢

转载自www.cnblogs.com/Coeus-P/p/9354879.html