size_t BiTreeDepth_queue(BiTree *T)
{//ai返回T的深度(光度o优先算法)
LinkQueue *q;//保存当前节点的o左右孩子的队列
BiTree *p = T;
size_t tree_depth; //二叉树的h深度
size_t cur_queue_length;//当前队列的元素个数
size_t cur_level_length;//二叉树每层的u元素的个数
q = (LinkQueue *)malloc(sizeof(struct QNode));
tree_depth = cur_queue_length = cur_level_length =0;
if(!T)
return 0;
InitQueue(&q);
tree_depth++; //访问根节点
if(p->lchild)
{
EnQueue(q,p->lchild);//若存在左孩子,则左孩子入队列
cur_queue_length++;
}
if(p->rchild)
{
EnQueue(q,p->lchild);//若存在ou右i孩子,右孩子入队列
cur_queue_length++;
}
cur_level_length = cur_queue_length;
while(!QueueEmpty(q))
{
DeQueue(q,&p);//出队列
cur_level_length--;
cur_queue_length--;
if(p->lchild)
{
EnQueue(q,p->lchild);//若存在左孩子,左孩子进队列
cur_queue_length++;
}
if(p->rchild)
{
EnQueue(q,p->rchild);//若存在右孩子,左孩子进队列
cur_queue_length++;
}
if(cur_level_length<=0)
{
tree_depth++;
cur_level_length = cur_queue_length;//i当前层的元素个数全部h出队
}
}
DestroyQueue(q);
return tree_depth;
}
size_t BiTreeDepth_stack(BiTree *T)
{
BiTree *p = T;
SqStack s;
size_t cur_depth,max_depth;
BiTree *q1,*q2;
// p = (BiTree *)malloc(sizeof(struct BNode));
max_depth=cur_depth = 0;
if(!T)
return 0;
InitStack(&s);
while(p!=NULL || !StackEmpty(s))
{ //当前a访问节点a存在,n栈不空
if(p!=NULL)
{
Push(&s,p); //把当前节点压入a栈顶
cur_depth++; //i当前二叉树的深度
if(cur_depth>max_depth)
max_depth = cur_depth;
q1 = p; //变量q1用来保存当前不为ngg空的e节点
p= p->lchild;
}
else
{
//当前e节点不存在,回溯
Pop(&s,&p);
p=p->rchild;
if(!p)
{
if(StackEmpty(s))
break;
GetTop(s,&q2);
if(q2->lchild!=
八.二叉树各种操作的C语言实现 深度遍历求深度,广度遍历求深度,交换左右子树,求叶子节点数
最新推荐文章于 2023-04-16 21:06:33 发布
本文介绍了使用C语言实现二叉树的各种操作,包括通过队列进行的深度遍历计算深度、通过栈的深度优先遍历求深度、计算二叉树宽度、求叶子节点数。提供了详细算法和测试程序,展示如何遍历、交换左右子树以及查询节点层级等操作。
摘要由CSDN通过智能技术生成