八.二叉树各种操作的C语言实现 深度遍历求深度,广度遍历求深度,交换左右子树,求叶子节点数

本文介绍了使用C语言实现二叉树的各种操作,包括通过队列进行的深度遍历计算深度、通过栈的深度优先遍历求深度、计算二叉树宽度、求叶子节点数。提供了详细算法和测试程序,展示如何遍历、交换左右子树以及查询节点层级等操作。
摘要由CSDN通过智能技术生成
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!=
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值