栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

2018年数据结构第五题(C/C++)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2018年数据结构第五题(C/C++)

题目:

我的代码实现:

#include
using namespace std;

#define TElemType int
typedef struct BiTNode{
 TElemType data;
 struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;

void CreateBiTree(BiTree &T)//先序建立二叉链表
{
 int ch;
 cin>>ch;
 if(ch==-1)T=NULL;
 else
 {
   T=new BiTNode;
   T->data=ch;
   CreateBiTree(T->lchild);
   CreateBiTree(T->rchild);
 }
}

//队列的存储结构定义及其操作.......................
#define MAXQSIZE 100
#define QElemType BiTNode*
typedef struct{
 QElemType *base;
 int front;
 int rear;
}SqQueue;

bool InitQueue(SqQueue &Q)
{
 Q.base=new QElemType[MAXQSIZE];
 if(!Q.base)exit(EOVERFLOW);
 Q.front=Q.rear=0;
 return true;
}

int QueueLength(SqQueue Q)
{
 return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;
}

bool EnQueue(SqQueue &Q,QElemType e)
{
 if((Q.rear+1)%MAXQSIZE==Q.front)return false;
 Q.base[Q.rear]=e;
 Q.rear=(Q.rear+1)%MAXQSIZE;
 return true;
}

bool DeQueue(SqQueue &Q,QElemType &e)
{
 if(Q.front==Q.rear)return false;
 e=Q.base[Q.front];
 Q.front=(Q.front+1)%MAXQSIZE;
 return true;
}
//...................................

//本题的解答(层序遍历思想).................................
int h1=-1,h2=-1;
void LocateTreeData(BiTree &T,int a,int b)
{
 int h=1;
 SqQueue Q;
 QElemType e;
 InitQueue(Q);//初始化队列Q
 EnQueue(Q,T);
 
 while(Q.front!=Q.rear)
 {
  int l=QueueLength(Q);//计算此时队列的长度
  while(l)
  {
   DeQueue(Q,e);
   if(e->data==a)h1=h;
   if(e->data==b)h2=h;
   l--;
   if(e->lchild)EnQueue(Q,e->lchild);
   if(e->rchild)EnQueue(Q,e->rchild);
  }
  h++;
 }
 
 if(h1==-1&&h2==-1)cout<<'n'<<-2<h2)cout<<'n'<lchild);
  DestroyTree(T->rchild);
  printf("销毁结点: %dn",T->data);
  delete T;
  T=NULL; 
 }
 return;
}

int main()
{
 BiTree T=NULL;
 printf("n构造二叉树:n");
 CreateBiTree(T);//构造二叉树T
 
 int a,b;
 printf("指定两个整数:n");
 cin>>a;
 cin>>b;
 
 LocateTreeData(T,a,b);//本题的解答
 
 DestroyTree(T);//销毁二叉树
}

算法思想:本题的解法基于层序遍历的思想,具体的来说基于队列操作,将每层结点的指针放入队列再出来,然后对每层的结点中的数值逐个检查,顺带将下一层的结点指针入队,这样下去直到所有结点的指针都经历了入队和出队为止

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/346848.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号