二叉树深度之非递归

#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();
}

杨帅彬个人博客分享更多技术

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值