⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tree.cpp

📁 以层次建立二叉树...................
💻 CPP
字号:
#include <iostream.h>
typedef struct BiTNode
{
 char ch;
 int nNum;
 struct BiTNode *lChild,*rChild;
}BiTNode,BTree,*BiTree;


typedef struct QueueNode
{
 BiTree data;
 struct QueueNode *next;
}QNode,*QueuePtr;
typedef struct
{
 QNode *front,*rear;
}LinkQueue;

bool InitQueue(LinkQueue &Q)
{
 Q.front =Q.rear =new(QueueNode);
 if(!Q.front ) return false;
 Q.front->next =NULL;
 Q.rear->next =NULL;
return true;
}

bool EnQueue(LinkQueue &Q,BiTree data)
{
 QueuePtr p=new(QueueNode);
 if(!p) {cout<<"Alloc error"<<endl; return false;}
 p->data =data;
 Q.rear ->next =p;
 Q.rear =p;

return true;
}
bool DeQueue(LinkQueue &Q,BiTree &data)
{
 if(Q.rear ==Q.front) return false;
 QueuePtr p=Q.front ->next ;
 data=p->data;
 Q.front->next =p->next ;
 if(Q.rear ==p) Q.rear =Q.front ;
 delete [] p;
return true;
}

BiTree CreNode()
{
 BiTree tree;
 tree=new(BiTNode);
 tree->ch=0;
 tree->lChild =NULL;
 tree->rChild =NULL;
 tree->nNum =0;
return tree;
}

BiTree LevelCreateTree()
{
 LinkQueue Q;
 InitQueue(Q);
  int n=1;
 int i;
 BiTree tree,p;
 cout<<"请输入虚结点个数:";
 cin>>i;
 char ch;
 tree=CreNode();
 EnQueue(Q,tree);
 while(n<=i)
 {
     DeQueue(Q,p);
     cin>>ch;
  if(ch=='@') break;
  p->ch=ch;
  p->nNum =n++;
  if(ch=='#')
  {
  p->lChild =NULL;
  p->rChild =NULL;
  }
  else
  { p->lChild =CreNode();
   p->rChild =CreNode();
  if(p->lChild) EnQueue(Q,p->lChild );
  if(p->rChild) EnQueue(Q,p->rChild );}
 }

return tree;
}
void PreTrav(BiTree tree)
{
 if(tree==NULL) return;
   cout<<"No:"<<tree->nNum<<"Value:"<<tree->ch<<endl;
   PreTrav(tree->lChild );
   PreTrav(tree->rChild );
}
LinkQueue LQ;
void TravelTree(BiTree tree)
{
 BiTree p;
 if(tree==NULL) return;
 EnQueue(LQ,tree);
 while(LQ.rear!=LQ.front )
 {
  DeQueue(LQ,p);
  cout<<"节点号:"<<p->nNum<<"值:"<<p->ch<<endl;
  if(p->lChild ) EnQueue(LQ,p->lChild);
  if(p->rChild ) EnQueue(LQ,p->rChild);
 }
}
void main()
{
 BiTree tree;
 InitQueue(LQ);
 tree=LevelCreateTree();
 cout<<"层次创建并层次遍历"<<endl;
 TravelTree(tree);
 cout<<"前序遍历"<<endl;
 PreTrav(tree);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -