二叉树按层遍历,该如何解决
二叉树按层遍历
二叉树按层遍历,输出时每层结束换行。如何用C++实现?
------解决方案--------------------
http://www.oschina.net/code/snippet_257994_10789
------解决方案--------------------
二叉树按层遍历,输出时每层结束换行。如何用C++实现?
------解决方案--------------------
http://www.oschina.net/code/snippet_257994_10789
------解决方案--------------------
- C/C++ code
#include<stdio.h> #include<stdlib.h> typedef struct btnode{ char data; struct btnode *lchild, *rchild; }BTNode; typedef struct{ BTNode elem[20]; int front,rear; }SqQueue; BTNode * CreatTree( void ); void Preorder(BTNode *bt ); void Inorder(BTNode *bt ); void Postorder(BTNode *bt ); void Levelsorder(BTNode *bt); void ExChangeLeafs(BTNode *bt); void EnQueue(SqQueue *sq,BTNode *bt); void DelQueue(SqQueue *sq,BTNode *p); void InitQueue(SqQueue *sq); main() { BTNode *t; char s[10]; for(;;) { printf("1--------CreatTree 2-----------Preorder \n"); printf("3--------Inorder 4-----------Postorder \n"); printf("5--------Levelsorder 6-----------ExchangeLeafs(Preorder) \n"); printf("7--------Exit\n"); gets(s); switch(*s) { case '1': t=CreatTree(); break; case '2': Preorder(t); printf("\n"); break; case '3': Inorder(t); printf("\n"); break; case '4': Postorder(t); printf("\n"); break; case '5': Levelsorder(t); printf("\n"); break; case '6': ExChangeLeafs(t); Preorder(t); printf("\n"); break; case '7': printf("exit \n"); exit(0); } } } #define MAXNUM 20 BTNode * CreatTree( void ) { int i=1,j;char ch; BTNode *p[MAXNUM+1],*t,*s; t=NULL; printf("\n enter i,ch: \n"); scanf("%d,%c",&i,&ch); while( i!=0 && ch!='#') { s=(BTNode *)malloc(sizeof(BTNode)); s->data=ch; s->lchild=s->rchild=NULL; p[i]=s; if(i==1) t=s; else { j=i/2; if(i%2==0) p[j]->lchild=s; else p[j]->rchild=s; } scanf("%d,%c",&i,&ch); } ch=getchar(); return t; } void Preorder(BTNode *bt ) { if (bt) { printf("%5c",bt->data); Preorder(bt->lchild); Preorder(bt->rchild); } } void Inorder(BTNode *bt ) { if (bt) { Inorder(bt->lchild); printf("%5c",bt->data); Inorder(bt->rchild); } } void Postorder(BTNode *bt ) { if (bt) { Postorder(bt->lchild); Postorder(bt->rchild); printf("%5c",bt->data); } } void ExChangeLeafs(BTNode *bt) { BTNode *temp; if(bt) { temp=bt->lchild; bt->lchild=bt->rchild; bt->rchild=temp; ExChangeLeafs(bt->lchild); ExChangeLeafs(bt->rchild); } } void Levelsorder(BTNode *bt) { BTNode p; SqQueue sq; InitQueue(&sq); EnQueue(&sq,bt); while(sq.front!=sq.rear) { DelQueue(&sq,&p); printf("%5c",p.data); if(p.lchild) EnQueue(&sq,p.lchild); if(p.rchild) EnQueue(&sq,p.rchild); } } void InitQueue(SqQueue *sq) { sq->front=sq->rear=0; } void EnQueue(SqQueue *sq ,BTNode *bt) { sq->elem[sq->rear]=*bt; sq->rear=(sq->rear+1)%20; } void DelQueue(SqQueue *sq,BTNode *p) { *p=sq->elem[sq->front]; sq->front=(sq->front+1)%20; }
------解决方案--------------------
用到队列 自己看吧
------解决方案--------------------
双向指针链表构建树 然后遍历
------解决方案--------------------