fork download
  1. //Initial Template for C++
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. struct Node
  6. {
  7. int data;
  8. struct Node *left, *right;
  9. };
  10.  
  11. Node* newNode(int data)
  12. {
  13. Node *temp = new Node;
  14. temp->data = data;
  15. temp->left = temp->right = NULL;
  16. return temp;
  17. }
  18.  
  19. void printInorder(Node* node)
  20. {
  21. if (node == NULL)
  22. return;
  23. printInorder(node->left);
  24. cout<<node->data<<" ";
  25. printInorder(node->right);
  26. }
  27.  
  28. void pairwiseSwap(Node **root)
  29. {
  30. // code here
  31. Node **firstPtr, **secondPtr;
  32. int count = 0;
  33. if ((*root) == NULL)
  34. return;
  35. if ((*root)->left == NULL && (*root)->right == NULL)
  36. {
  37. count++;
  38. if (count%2)
  39. swap(firstPtr, secondPtr);
  40. else
  41. firstPtr = secondPtr;
  42.  
  43. }
  44. pairwiseSwap(&(*root)->left);
  45. pairwiseSwap(&(*root)->right);
  46. }
  47.  
  48. int main()
  49. {
  50. int t;
  51. scanf("%d", &t);
  52. while (t--)
  53. {
  54. map<int, Node*> m;
  55. int n;
  56. scanf("%d",&n);
  57. struct Node *root = NULL;
  58. struct Node *child;
  59. while (n--)
  60. {
  61. Node *parent;
  62. char lr;
  63. int n1, n2;
  64. scanf("%d %d %c", &n1, &n2, &lr);
  65. if (m.find(n1) == m.end())
  66. {
  67. parent = newNode(n1);
  68. m[n1] = parent;
  69. if (root == NULL)
  70. root = parent;
  71. }
  72. else
  73. parent = m[n1];
  74. child = newNode(n2);
  75. if (lr == 'L')
  76. parent->left = child;
  77. else
  78. parent->right = child;
  79. m[n2] = child;
  80. }
  81. pairwiseSwap(&root);
  82. printInorder(root);
  83. cout<<" ";
  84. }
  85. return 0;
  86. }
Success #stdin #stdout 0s 15240KB
stdin
2
2
1 2 R 1 3 L
4
10 20 L 10 30 R 20 40 L 20 60 R
stdout
3 1 2  40 20 60 10 30