Time limit 1000 ms memory limit 65536 KB
Title Description
The teacher wants to test mabo, but mabo can't, so he wants to ask you for help.
The questions are as follows:
Give a binary tree
Please print this binary tree by layer. If it is the same layer, you need to print from left to right. One node is to add the left node first and then the right node, that is, the order of adding is the same as the order of input.
Input format
First, input an integer T, indicating that there are t groups of data 0 < T < = 10
Enter two more integers n, m (0 < = n, m < = 100)
Indicates that there are N rows below, and there are M nodes in this tree (node 1 is the root node of this tree)
Two integers a, B for each line (1 < = a, B < = m)
Indicates that the father of node a is node b
Output format
For each group
Output a line "Qi:" to indicate the ith problem
Then output the nodes of each layer of each problem binary tree. The nodes in the same layer are separated by spaces. The output of the same layer is in one line (there is no space at the end of each line), and the output of different layers is in different lines (as shown in Sample Ouput below)
sample input
2 4 5 2 1 3 1 4 2 5 4 1 2 2 1
sample output
Q1: 1 2 3 4 5 Q2: 1 2
AC code
#include<bits/stdc++.h> #define MAXN 110 using namespace std; struct node{ vector<int > child; }BNode[110]; void initTree(int line,int cnt){ for(int i=1;i<=cnt;i++){ BNode[i].child.clear(); } int son,father; while(line--){ scanf("%d%d",&son,&father); BNode[father].child.push_back(son); } } void levelOrder(int root,int num){ printf("Q%d:\n",num); queue<int > q; q.push(root); while(!q.empty()){ int size_q = q.size(); while(size_q--){ int front_q = q.front(); q.pop(); printf("%d",front_q); if(size_q){ printf(" "); } else{ printf("\n"); } vector<int>& v = BNode[front_q].child; for(unsigned int i=0;i<v.size();i++){ q.push(v[i]); } } } } int main() { int t,n,m; scanf("%d",&t); for(int i=1;i<=t;i++){ scanf("%d%d",&n,&m); initTree(n,m); levelOrder(1,i); } }