【问题标题】:Printing Binary Tree levels in sorted order按排序顺序打印二叉树级别
【发布时间】:2020-08-30 06:10:11
【问题描述】:

给定一个数组arr[],其中包含完整二叉树的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;
}

错误:超出输出限制!!!

【问题讨论】:

标签: c++ data-structures queue priority-queue


【解决方案1】:

这段代码

          while(m.empty()==false)
            {
                cout<<m.top()<<" ";
            }

是一个无限循环。也许你的意思是这样的(只是猜测)

          while (!m.empty())
          {
              cout << m.top() << " ";
              m.pop();
          }

【讨论】:

  • 是的!你没看错就是导致错误!!
猜你喜欢
  • 1970-01-01
  • 2012-10-22
  • 2020-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-22
  • 2011-01-15
  • 2010-12-26
相关资源
最近更新 更多