根据层次遍历的顺序建立树,树的层次遍历

来源:互联网 发布:sql server 回滚 编辑:程序博客网 时间:2024/05/19 16:47
//根据层次遍历的顺序建立树 #include #include //树的存储类型 typedef struct tree { char data; tree *lchild,*rchild; tree *next; }tree,*stree; //队列的存储类型 typedef struct queue { stree head; stree tail; }queue; queue s1,s2; //队列的初始化 void Init(queue &s) { s.head=NULL;s.tail=NULL; } //入队列操作 void In(queue &s,stree pp) { if(s.head==NULL) {s.head=pp;s.tail=pp;s.tail->next=NULL;} else { s.tail->next=pp; s.tail=pp; } } //取队列的对头的操作 stree GetHead(queue s) { return s.head; } //删除队列的对头 void pop(queue &s) { stree p=NULL; if(s.head) { p=s.head->next; s.head=p; } else s.head=NULL; } void pre(stree t) { if(t) { printf("%c ",t->data); pre(t->lchild); //printf("%c ",t->data); pre(t->rchild); } } void creat_tree(stree &t) { stree p,temp,r; //snode pp; char fa,ch; t=NULL; for(scanf("%c%c",&fa,&ch);ch!='#';scanf("%c%c",&fa,&ch)) { //printf("%c,%c/n",fa,ch); p=(stree)malloc(sizeof(tree)); p->data=ch;p->lchild=NULL;p->rchild=NULL; //原来这里不可以少啊 p->next=NULL; if(fa=='#') t=p; else { temp=GetHead(s1); while(temp->data!=fa) { pop(s1);temp=GetHead(s1); } if(temp->lchild==NULL) {temp->lchild=p;r=p;} else {r->rchild=p;r=p;} } //pp=(snode)malloc(sizeof(node));pp.data=ch; In(s1,p); getchar(); } } int Empty(queue q) { if(q.head==NULL) return 1; else return 0; } //层次遍历二叉树(类似广度优先搜索) void level(stree t) { stree p; if(t) { p=t;//In(s2,p); while(1) { while(p) { printf("%c ",p->data); In(s2,p); p=p->rchild; } if(Empty(s2)) break; p=GetHead(s2); if(p!=NULL) p=p->lchild;/////////////////////////////////////////////// else p=NULL;///////////////////////////// pop(s2); } } } void main() { stree t; Init(s1); Init(s2); creat_tree(t); printf("树对应的二叉树的先序遍历:/n"); pre(t); printf("/n"); printf("树对应的二叉树的层次遍历:/n"); level(t); printf("/n"); } /* #a ab ac ad be cf di dj fg fh jk ## 树对应的二叉树的先序遍历: a b e c f g h d i j k 树对应的二叉树的层次遍历: a b c d e f i j g h k Press any key to continue */