数据结构-二叉树的层序遍历

(1)通过代码能够找到二叉树的深度

#define MAXSIZE 100
#include<bits/stdc++.h>
using namespace std;
typedef char TreeType;
struct TreeNode
{
	TreeType data;
	struct TreeNode *lchild;
	struct TreeNode *rchild;
};
typedef TreeNode* ElemType;
struct Queue{
	ElemType *data;
	int front;
	int rear;
};
typedef TreeNode* BiTree;
string str="ABDH#K###E##CFI###G#J##";
int indx=0;
void createTree(BiTree *T)
{
    TreeType ch;
    ch=str[indx++];
    if(ch=='#')
    {
        *T=NULL;
    }
    else
    {
        *T=new TreeNode;
        (*T)->data=ch;
        createTree(&(*T)->lchild);
        createTree(&(*T)->rchild);
    }
}
Queue * initQueue(){
    Queue *q=new Queue;
    q->data=new ElemType[MAXSIZE];
    q->front=0;
    q->rear=0;
    return q;
}
int isEmpty(Queue *Q){
    if(Q->front==Q->rear){
        cout<<"空的"<<endl;;
        return true;
    }
    else
    {
        return false;
    }
}
int equeue(Queue *Q,ElemType e)
{
    if((Q->rear+1)%MAXSIZE==Q->front)
    {
        cout<<"满了"<<endl;
        return 0;
    }
    Q->data[Q->rear]=e;
    Q->rear=(Q->rear+1)%MAXSIZE;
    return true;
}
int dequeue(Queue *Q,ElemType *e)
{
    if(Q->front==Q->rear)
    {
        cout<<"空的"<<endl;
        return 0;
    }
    *e=Q->data[Q->front];
    Q->front=(Q->front+1)%MAXSIZE;
    return true;
}
int getHead(Queue *Q,ElemType *e)
{
    if(Q->front==Q->rear)
    {
        cout<<"空的"<<endl;
        return 0;
    }
    *e=Q->data[Q->front];
    return 1;
}
int queueSize(Queue *Q)
{
	if(!isEmpty(Q))
	{
		return Q->rear-Q->front;
	}
	else 
	{
		return 0;
	}
}
int maxDepth(TreeNode* root)
{
	if(root==NULL)
	{
		return 0;
	}
	int depth=0;
	Queue *q=initQueue();
	equeue(q,root);
	while(!isEmpty(q))
	{
		int count=queueSize(q);
		while(count>0)
		{
			TreeNode* curr;
			dequeue(q,&curr);
			if(curr->lchild!=NULL)
			{
				equeue(q,curr->lchild);
			}
			if(curr->rchild!=NULL)
			{
				equeue(q,curr->rchild);
			}
			count--;
		}
		depth++;
	}
	return depth;
}
int main()
{
	BiTree T;
	createTree(&T);
	cout<<maxDepth(T)<<endl;
}
全部评论

相关推荐

点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务