Perform hierarchical traversal. After accessing the nodes of a certain layer, access the Left and Right nodes of each node in the order of their access. In this way, the left and right nodes that are accessed first need to be accessed first, which is consistent with the queue operation principles. Therefore, the hierarchical traversal algorithm is implemented using a ring queue.
The process of layered traversal:
First, enter the root node into the team. When the team is not empty, cycle: Column A node * P from the queue to access it; if it has a left child node, enter the left child node into the team; if it has a right child node, the right child enters the team. This operation continues until the team is empty. The algorithm is as follows:
1 void levelorder (TREE * root) 2 {3 tree * P; 4 tree * que [FB]; // defines the ring queue and stores the node pointer 5 Int front and rear; // define the first 6 front = rear =-1; // set the queue to an empty queue 7 rear ++; 8 que [rear] = root; // The root node pointer enters the Team 9 While (front! = Rear) {// The queue is not empty. 10 front = (front + 1) % FB; 11 p = que [Front]; // The first-out queue 12 cout <p-> nodenum <""; // 13 if (p-> left! = NULL) {// 14 rear = (Rear + 1) % FB; 15 que [rear] = p-> left; 16} 17 if (p-> right! = NULL) {// team 18 rear = (Rear + 1) % FB; 19 que [rear] = p-> right; 20} 21} 22}
Layered traversal of Binary Trees