求二叉树深度的非递归算法

#include <stdio.h>
#include <string.h>
#define     maxleng   100
#define     TRUE  1
#define     FALSE  0
#define     OK   1
#define     ERROR  0
#define     OVERFLOW -2
/*------------------------------------------------------*/
typedef int status;
typedef char TElemType;
typedef struct BiTNode{
    TElemType  data;
    struct BiTNode  *lchild, *rchild;
}BiTNode, *BiTree;

status  CreateBiTree(BiTree  *T);
int Depth1(BiTree T );
void display(TElemType e);

void main()
{
int i;
BiTree T;
CreateBiTree(&T);
printf("%d",Depth1(T));
}
status  CreateBiTree(BiTree  *T) {
    //按先序次序输入二叉树中结点的值(字符),空格符表示空树,
    //构造二叉链表表示的二叉树。
    char ch;
    ch = getchar();//scanf("%c",&ch);
    if (ch==' ') *T = NULL;
    else {
        *T = (BiTNode *)malloc(sizeof(BiTNode));
        if (!(*T))exit(OVERFLOW);
        (*T) -> data = ch; // 生成根结点
        CreateBiTree(&((*T)->lchild)); // 构造左子树
        CreateBiTree(&((*T)->rchild)); // 构造右子树
    }
    return OK;
} // CreateBiTree

int Depth1(BiTree T )
{
    int top = 0;
    int depth = 0,temp = 0;//temp 保存当前单分支的最大值
    BiTree p = T;
    BiTree nodePointer[maxleng-1];
    while(p || top > 0){
        if(p){
            nodePointer[top] = p;
            ++ top;
            ++ depth; //统计单分支的深度
            p = p->lchild;
        }
        else{
            -- top;
            p = nodePointer[top];
            p = p->rchild;
            if(p == NULL)
            { //单分支结束
                if(depth > temp )
                temp = depth;
                -- depth;
            }
        }//else
    }//while
    return temp;
}

void display(TElemType e){
    printf("%c ",e);

}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值