fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct Node
  5. {
  6. int key;
  7. struct Node *left;
  8. struct Node *right;
  9. Node(int k){
  10. key=k;
  11. left=right=NULL;
  12. }
  13. };
  14.  
  15. void inorder(Node *root){
  16. if(root!=NULL){
  17. inorder(root->left);
  18. cout<<root->key<<" ";
  19. inorder(root->right);
  20. }
  21. }
  22.  
  23. Node *prevv=NULL,*first=NULL,*second=NULL;
  24. void fixBST(Node* root)
  25. {
  26. if (root == NULL)
  27. return;
  28. fixBST(root->left);
  29. if(prevv!=NULL && root->key<prevv->key){
  30. if(first==NULL)
  31. first=prevv;
  32. second=root;
  33. }
  34. prevv=root;
  35.  
  36. fixBST(root->right);
  37. }
  38.  
  39. int main() {
  40.  
  41. Node *root = new Node(18);
  42. root->left = new Node(60);
  43. root->right = new Node(70);
  44. root->left->left = new Node(4);
  45. root->right->left = new Node(8);
  46. root->right->right = new Node(80);
  47.  
  48. inorder(root);
  49. cout<<endl;
  50. fixBST(root);
  51. int temp=first->key;
  52. first->key=second->key;
  53. second->key=temp;
  54. inorder(root);
  55.  
  56. return 0;
  57.  
  58. }
Success #stdin #stdout 0s 5496KB
stdin
Standard input is empty
stdout
4 60 18 8 70 80 
4 8 18 60 70 80