// Create a tree in the order of layered traversal # include # Include // Tree storage type typedef struct tree {char data; tree * lchild, * rchild; tree * Next;} tree, * stree; // queue storage type typedef struct queue {stree head; stree tail;} queue; queue S1, S2; // queue initialization void Init (queue & S) {S. head = NULL; S. tail = NULL;} // The 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 ;}// get the operation stree gethead (queue s) {retu Rn S. head;} // Delete the header of the queue 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", & FA, & Ch); ch! = '#'; Scanf ("% C", & FA, & Ch) {// printf ("% C, % C/N", fa, ch); P = (stree) malloc (sizeof (tree); P-> DATA = CH; P-> lchild = NULL; P-> rchild = NULL; // It cannot be missing here. 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;} // layered traversal of a binary tree (similar to a breadth-first search) 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) B Reak; 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 ("sequential traversal of the Binary Tree corresponding to the tree:/N "); pre (t); printf ("/N"); printf ("layered traversal of the tree's Binary Tree:/N"); level (t ); printf ("/N");}/* # a AB AC ad be CF di DJ FG FH JK # first traversal of the Binary Tree corresponding to the tree: hierarchical traversal of the Binary Tree corresponding to a B e c f g h I j k: a B c d e f I J G H K press any key to continue */
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.