问题描述
给出一个数组arr[]
,该数组包含以级别顺序方式包含Complete Binary树的N
个节点的数据。任务是按排序顺序打印级别顺序遍历。
输入: 输入的第一行包含整数T,表示测试用例的数量。对于每个测试用例,第一行都使用整数n来表示数组的大小,即节点数,然后是用n个空格分隔的整数,以级别顺序表示树的节点。
输出: 对于每个测试用例,输出是级别顺序排序的树。 注意:对于每个级别,我们仅打印不同的元素。
输入:
2
7
7 6 5 4 3 2 1
6
5 6 4 9 2 1
输出:
7
5 6
1 2 3 4
5
4 6
1 2 9
代码:
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main() {
//code
int t;
cin>>t;
while(t--)
{priority_queue<int,vector<int>,greater<int>> m;
int a;
cin>>a;
int k=1;
int arr[a];
queue<int> s;
for(int i=0;i<a;i++)
{
cin>>arr[i];
s.push(arr[i]);
}
while(s.empty()==false)
{
if(m.size()==k)
{
while(m.empty()==false)
{
cout<<m.top()<<" ";
}
k=k*2;
cout<<endl;
}
else
{
m.push(s.front());
s.pop();
}
}
if(m.empty()==false)
{
while(m.empty()==false)
{
cout<<m.top()<<" ";
}
cout<<endl;
}
}
return 0;
}
解决方法
此代码
while(m.empty()==false)
{
cout<<m.top()<<" ";
}
是一个无限循环。也许你的意思是这样(只是猜测)
while (!m.empty())
{
cout << m.top() << " ";
m.pop();
}