fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. class Node {
  5. public:
  6. int data;
  7. Node* right;
  8. Node* left;
  9.  
  10. Node(int data) {
  11. this->data = data;
  12. this->right = nullptr;
  13. this->left = nullptr;
  14. }
  15.  
  16. void level_order_traversal_sorted() {
  17. if (!this) return;
  18.  
  19. queue<Node*> q;
  20. q.push(this);
  21.  
  22. while (!q.empty()) {
  23. int count = q.size();
  24. vector<Node*> level_nodes;
  25.  
  26. for (int i = 0; i < count; i++) {
  27. Node* temp = q.front();
  28. q.pop();
  29. level_nodes.push_back(temp);
  30.  
  31. if (temp->left) q.push(temp->left);
  32. if (temp->right) q.push(temp->right);
  33. }
  34.  
  35. sort(level_nodes.begin(), level_nodes.end(), [](Node* a, Node* b) {
  36. return a->data > b->data;
  37. });
  38.  
  39. for (auto node : level_nodes) {
  40. cout << node->data << " ";
  41. }
  42. cout << endl;
  43. }
  44. }
  45. };
  46. int main(){
  47.  
  48.  
  49. Node* root = new Node(25);
  50. root->left = new Node(3);
  51. root->left->left = new Node(5);
  52. root->right = new Node(7);
  53. root->right->left = new Node(30);
  54. root->right->right = new Node(6);
  55. root->level_order_traversal_sorted();
  56. return 0;
  57. }
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
25 
7 3 
30 6 5