C Language implementation by hierarchy (breadth first) non-recursive traversal of binary chain tree

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.