Binary tree sequence traversal is from the top down, from the left and right to access each node, but in order to do so, the adjacent access to the two nodes are mostly not directly linked, difficult to access, so it will appear more troublesome, but we have a queue this good thing, build a sequential table queue, the address of each node in order to deposit, This is followed by sequential access in the queue. The key is whether the queue can exactly store each node in order from top to bottom, from left to right. Consider the following analysis.
local Indicates the position of the node currently being accessed in the queue, and length indicates the queue size. Local=0 when accessing a, you can add B, c to the queue, length=3; When Local=1 accesses B, it is possible to place D and E in the tail of the team, and the order of elements in the queue conforms to "sequence", and so on. It is clear that the length maximum will be a total of two fork tree elements, local=length when the last element is finally scanned, ending the loop at this point. The implementation code is as follows:
1 #defineSize_of_queue 2562 //Lchild point to left dial hand tree3 //Rchild refers to the right sub-tree4typedefstructbtree{5 intdata;6 structBTree *Lchild;7 structBTree *Rchild;8 }BT;9 Ten voiddisplaybylevel (BT root) { One BT Queue[size_of_queue]; A intLocal; - intlength; -queue[0] =Root; theLocal =0; -Length =1; - while(Local <length) { -printf"%d\n", queue[local]->data); + if(Queue[local]->lchild! =NULL) -queue[length++] = queue[local]->Lchild; + if(Queue[local]->rchild! =NULL) Aqueue[length++] = queue[local]->Rchild; atlocal++; - } -}
Sequence traversal of binary tree