1#include <stdio.h>2#include <conio.h>
4#include <malloc.h>5typedefChardatatype; Character type content6typedefstructnode{//Two fork chain tree data structure7 datatype data;8 structNode *lchild,*Rchild;9 }bitree;TenBitree *Creattree () {///The function of building a two-fork chain Tree is exactly the same as here, welcome to a comment about building a tree One Charch; ABitree *q[ -]; - intfront,rear; -Bitree *root,*s; theroot=NULL; -Front=1, rear=0; - while((Ch=getchar ())! ='#') - { +s=NULL; - if(ch!='@'){ +S= (bitree*)malloc(sizeof(Bitree)); AS->data=ch; atS->lchild=NULL; -S->rchild=NULL; - } -rear++; -q[rear]=s; - if(rear==1) inroot=s; - Else{ to if(s&&Q[front]) { + if(rear%2==0) -Q[front]->lchild=s; the Else *Q[front]->rchild=s; $ }Panax Notoginseng if(rear%2==1) -front++; the } + } A returnRoot; the } + voidBianli (Bitree *p) The {///level traversal function of the binary tree, in fact, is similar to the idea of building a two-fork tree, all using the following "queue array", where p is the root node of the tree to be accessed -Bitree *q[ -]; Queue array, holding bitree node pointers $Bitree *s; The currently traversed node $ intRear=1, front=0; -q[rear]=p; The first knot of the head p queue - while(front<rear) {//queue array is not empty, enter (continue) loop thefront++; -s=Q[front]; The current node is enqueuedWuyiprintf"%c",s->data); accessing elements the if(s->lchild!=NULL)//left child is present, then the left child is in the queue - { Wurear++; -Q[rear]=s->Lchild; About } $ if(s->rchild!=NULL) //Right child is present, then the right child is in the queue - { -rear++; -Q[rear]=s->Rchild; A } + } the } - intMain () $ { theBitree *Root; theroot=Creattree (); the Bianli (root); the return 0; -}
You can also switch the end prompt to the next line of input:
C Language implementation by hierarchy (breadth first) non-recursive traversal of binary chain tree