#include <stdio.h>
#include <malloc.h>
typedef int ElemType;
#define MaxSize 50
typedef struct node
{
ElemType data;
struct node *lchild;
struct node *rchild;
}BTNode;
typedef struct
{
BTNode *data[MaxSize];
int front,rear;
}SqQueue;
// 创建二叉树
void CreateBTree(BTNode *&b,char *str)
{
BTNode * St[MaxSize],*p;
int top=-1,k,j=0;
char ch;
b=NULL;
ch=str[j];
while(ch!='\0')
{
switch (ch)
{
case '(':top++;St[top]=p;k=1;break;
case ')':top--;break;
case ',':k=2;break;
default:p=(BTNode*)malloc(sizeof(BTNode));
p->data=ch;
p->lchild=p->rchild=NULL;
if(b==NULL)
b=p;
else
{
switch (k)
{
case 1:St[top]->lchild=p;break;
case 2:St[top]->rchild=p;break;
}
}
}
j++;
ch=str[j];
}
}
// 销毁二叉树
void DestroyBTree(BTNode *& b)
{
if(b!=NULL)
{
DestroyBTree(b->lchild);
DestroyBTree(b->rchild);
free(b);
}
}
void DispBTree(BTNode *b)
{
if(b!=NULL)
{
printf("%c",b->data);
if(b->lchild!=NULL || b->rchild!=NULL)
{
printf("(");
DispBTree(b->lchild);
if(b->rchild!=NULL)
printf(",");
DispBTree(b->rchild);
printf(")");
}
}
}
// 初始化队列
void InitQueue(SqQueue *&q)
{
q=(SqQueue*)malloc(sizeof(SqQueue));
q->front=q->rear=-1;
}
// 销毁队列
void DestroyQueue(SqQueue *&q)
{
free(q);
}
// 判断队列是否为空
bool QueueEmpty(SqQueue *q)
{
return(q->front==q->rear);
}
// 入队
bool enQueue(SqQueue *&q,BTNode* b)
{
if(q->rear==MaxSize-1)
return false;
q->rear++;
q->data[q->rear]=b;
return true;
}
// 出队
bool deQueue(SqQueue *&q,BTNode* &b)
{
if(q->front==q->rear)
return false;
q->front++;
b=q->data[q->front];
return true;
}
// 非递归求树的深度
int BTHeight(BTNode * b)
{
int depth=0,hp,tp,lc;
SqQueue *Q;
BTNode *p;
if(b)
{
p=b;
hp=0;tp=1;lc=1;
InitQueue(Q);
enQueue(Q,p);
while(!QueueEmpty(Q))
{
deQueue(Q,p);
hp++;
if(p->lchild)
{
enQueue(Q,p->lchild);
tp++;
}
if(p->rchild)
{
enQueue(Q,p->rchild);
tp++;
}
if(hp==lc)
{
depth++;
lc=tp;
}
}
}
DestroyQueue(Q);
return depth;
}
void main()
{
BTNode *b;
CreateBTree(b,"A(B(D(,G)),C(E,F))");
DispBTree(b);
int depth=BTHeight(b);
printf("\n二叉树深度:%d",depth);
DestroyBTree(b);
getchar();
}
二叉树深度之非递归
猜你喜欢
转载自blog.csdn.net/a47915694/article/details/80977024
今日推荐
周排行