C++ breadth-first search, search binary tree, and print

Breadth First Search (BFS)

What is Breadth First Search

Breadth-first search is layer-order traversal, searching the entire graph layer by layer

Code implementation of BFS

Use an array to implement a static binary tree. The structure of the tree is shown below

 

The code is shown below

 #include "stdio.h"
 #include "queue"
 using namespace std;
 ​
 const int N=100005;
 //Static array of nodes
 struct Node{
     char value;
     int lson, rson;
 ​
 }tree[N];
 //subscript
 int index=1;
 // get a new node
 int newNode(char value){
     tree[index].value=value;
     tree[index].lson=0;
     tree[index].rson=0;
     return index++;
 }
 //insert a new node
 void insertNode(int &father,int child,int l_r){
     if(l_r==0){
         tree[father].lson=child;
     }else{
         tree[father].rson=child;
     }
 }
 //build a tree
 int buildTree(){
     int A= newNode('A');
     int B= newNode('B');
     int C= newNode('C');
     int D= newNode('D');
     int E= newNode('E');
     int F= newNode('F');
     int G= newNode('G');
     int H= newNode('H');
     int I= newNode('I');
 ​
     insertNode(E,B,0);
     insertNode(E,G,1);
     insertNode(B,A,0);
     insertNode(B,D,1);
     insertNode(G,F,0);
     insertNode(G,I,1);
     insertNode(D,C,0);
     insertNode(I,H,0);
 ​
     return E;
 }
 ​
 int main(){
 ​
 // Generate this tree and get the root node of this tree
     int root=buildTree();
 // queue
     queue<int> q;
 // Put the root node at the back of the queue
     q.push(root);
 // if the queue is not empty
     while (q.size()){
 // get previous node
         int tmp=q.front();
 // print this node
         printf("%c\t",tree[tmp].value);
 // This node has been used, discard it directly
         q.pop();
 // If the child nodes of the tmp node are not empty, add these child nodes to the end of the queue
         if(tree[tmp].rson!=0)q.push(tree[tmp].rson);
         if(tree[tmp].lson!=0)q.push(tree[tmp].lson);
     }
     return 0;
 }

Guess you like

Origin blog.csdn.net/weixin_53064820/article/details/130541470