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

//根据层次遍历的顺序建立树 #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 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值