In the last article, I did a simple exercise on binary tree, and also got a general understanding of binary tree. Next, I will discuss the key algorithm in binary tree, namely the hierarchical traversal of binary tree, namely BFS.
The importance of this algorithm is not to say much, it is mainly used to solve the single source shortest path problem (weightless tree).
BFS - Width First Traversal
As the name implies: first traverse the state closest to the initial state, then traverse the state closest to the traversed state. From the start state --> the state that can be reached only once --> the state that can be reached only twice -->... ..
As in the previous article, the binary tree
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
How do you traverse it according to BFS?
(1) traverse from the beginning; (2) traverse the nearest nodes of 1, i.e. 2 and 3; (3) traverse the nearest nodes of 2 and 3, i.e. 4, 5, 6, 7; (4) traverse the nearest nodes of 4, 5, 6, 7, i.e. 8, 9, 10, 11, 12, 13, 14, 15. Complete.
How to implement BFS?
Answer: Queue. Imagine the characteristics of the queue - FIFO (first in first out), ok, so let's simulate the process of the nodes entering and leaving the queue.
(1) Create an empty queue q;
(2) Enter node 1 into the queue; queue status is: 1
(3) Loop (the following steps are completed in this loop), if the queue q is empty, because if all nodes are no longer in the queue, the traversal is completed;
(4) Take the first node of the queue and assign it to the new node V, then leave the queue, that is, node 1. At present, the queue is empty, and node V is node 1. The queue status is NULL.
(5) Find all the nodes adjacent to V, i.e. nodes 2 and 3, and then join the queue; the queue status is: 23
(6) Take the head element of the queue, i.e. node 2, assign it to V, and then leave the queue; the queue state is: 3.
(7) Find all the nodes adjacent to V, i.e. nodes 4 and 5, and then join the queue: the queue status is 345
(8)... No further elaboration on the process
This is the basic process. The idea of finding the shortest path (without power) is the same. Each node has a dis value, which means the shortest distance from the beginning to one of the nodes. The process is basically the same as above, that is to initialize the dis value of all nodes to 0, and then traverse to a node, so that the dis of this node is equal to the dis+1 of its parent node.
- Examples. Hierarchical traversal of trees - UVA122
An example is given in the algorithmic introductory classics. Let's analyze it.
Problem Description: Input a binary tree, and then output the values of each node from top to bottom, left to right. Each node is given according to the sequence of movement from the root node to it (L for left and R for right).
Sample input: (11, LL) (7, LLL) (8, R) (5,) (4, L) (13, RL) (2, LLR) (1, RRR) (4, RR) ()
Sample output: 548 11 13 4 7 2 1
The bfs of this topic is implemented by queues according to the ideas I just sorted out. In fact, I think the difficulty lies in how to input according to the requirements of the topic and save the nodes. According to Liu Rujia's code analysis.
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
const int maxn = 256+10;
struct Node{
bool have_value;
int v;//Used to save node values
Node *left,*right;
Node():have_value(false),left(NULL),right(NULL){}
};//Define a node structure
Node* newnode()
{
return new Node();
}//Create new node functions
char s[maxn];
Node* root;
bool failed;
void addnode(int v,char* s)
{
int n = strlen(s);
Node* u = root;
for(int i=0;i<n;i++)
{
if(s[i]=='L')
{
if(u->left==NULL) u->left = newnode();//If the node does not exist, create a new node
u = u->left;//Go left to the new building.
}
else if(s[i]=='R')
{
if(u->right==NULL) u->right = newnode();
u = u->right;
}
}
if(u->have_value) failed = true;//Has been assigned, indicating that the input is incorrect
u->v = v;
u->have_value = true;//Marking
}
bool read_input()
{
failed = false;
root = newnode();
for(;;)
{
if(scanf("%s",s)!=1) return false;
if(!strcmp(s,"()")) break;//If the input is "()", that is the end of the input, exit the loop directly.
int v;
sscanf(&s[1],"%d",&v);//Read out the node value in the string and assign it to V
addnode(v,strchr(s,',')+1);//The strchr function returns, first appears, and then inserts the node.
}
return true;
}
bool bfs(vector<int>& ans)
{
queue<Node*> q;
ans.clear();//Before each traversal, reset the vector, i.e. empty it
q.push(root);//Put the root node in the queue first
while(!q.empty())//Judge whether it is empty
{
Node* u = q.front();q.pop();//Take the head node of the team and assign it to u and join the team
if(!u->have_value) return false;//If the node is not assigned, the input is incorrect
ans.push_back(u->v);//Insert the value of the current node into the vector
if(u->left!=NULL)
{
q.push(u->left);//If the left sub-node is not empty, the left sub-node will join the team.
}
if(u->right!=NULL)
{
q.push(u->right);
}
}
return true;
}
int main()
{
vector<int> v;
while(read_input())
{
if(!bfs(v)) failed = 1;
if(failed) printf("not complete\n");
else{
for(int i=0;i<v.size();i++)
{
if(i != 0) printf(" ");
printf("%d", v[i]);
}
printf("\n");
}
}
return 0;
}
The value of this problem is still very large, through the vector to save the traversal node value, while traversing while preserving.