Layered traversal of Binary Trees

Source: Internet
Author: User

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

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.