fork download
  1. #include <iostream>
  2. #include <queue>
  3. using namespace std;
  4.  
  5. struct Node{
  6. int data;
  7. Node *left, *right;
  8. Node(int x) {
  9. data=x;
  10. left=right=NULL;
  11. }
  12. };
  13.  
  14. void insert(Node* &root, int x) {
  15. if (root==NULL){
  16. root = new Node(x);
  17. return;
  18. }
  19. if (root->data>x) insert(root->left, x);
  20. if (root->data<x) insert(root->right, x);
  21. }
  22.  
  23. void rightLevelOrder(Node* root) {
  24. if (root==NULL) return;
  25.  
  26. queue<Node*> q;
  27. q.push(root);
  28.  
  29. while (!q.empty()) {
  30. int level_size = q.size();
  31. while (level_size--) {
  32. Node* curr = q.front(); q.pop();
  33. cout<<curr->data<<" ";
  34. if (curr->right) q.push(curr->right);
  35. if (curr->left) q.push(curr->left);
  36. }
  37. }
  38. cout << endl;
  39. }
  40.  
  41. int main() {
  42. int t; cin >> t;
  43. while (t--) {
  44. int n;
  45. cin >> n;
  46. int a[10005];
  47. for (int i=0;i<n;i++) {
  48. cin>>a[i];
  49. }
  50. Node* root=NULL;
  51. for (int i=0;i<n;i++) {
  52. insert(root, a[i]);
  53. }
  54.  
  55. rightLevelOrder(root);
  56. }
  57.  
  58. return 0;
  59. }
  60.  
Success #stdin #stdout 0.01s 5316KB
stdin
Standard input is empty
stdout
Standard output is empty