fork download
  1. #include<iostream>
  2. #include<vector>
  3. using namespace std;
  4.  
  5. //Node Structure
  6. class Node {
  7. public:
  8. int data;
  9. Node* left;
  10. Node* right;
  11.  
  12. Node(int x) {
  13. data = x;
  14. left = right = nullptr;
  15. }
  16.  
  17. };
  18.  
  19.  
  20. vector<int> inOrder(Node* root) {
  21. vector<int> res;
  22.  
  23. Node* curr = root;
  24.  
  25. while(curr != nullptr) {
  26. if(curr->left == nullptr) {
  27.  
  28. //if no left child, visit this node
  29. //and go right
  30. res.push_back(curr->data);
  31. curr = curr->right;
  32. }
  33. else {
  34. //Find the inorder predecessor of curr
  35. Node* prev = curr->left;
  36.  
  37. while(prev->right!= nullptr && prev->right!= curr) {
  38. prev = prev->right;
  39.  
  40. }
  41.  
  42. if(prev->right == nullptr) {
  43. prev->right = curr;
  44. curr = curr->left;
  45. }
  46. else {
  47. //Revert the changes made in the tree
  48. prev->right = nullptr;
  49. res.push_back(curr->data);
  50. curr = curr->right;
  51. }
  52.  
  53. }
  54.  
  55. }
  56.  
  57. return res;
  58.  
  59. }
  60.  
  61. int main() {
  62.  
  63. Node* root = new Node(1);
  64. root->left = new Node(2);
  65. root->right = new Node(3);
  66. root->left->left = new Node(4);
  67. root->left->right = new Node(5);
  68.  
  69. vector<int> res = inOrder(root);
  70.  
  71. for(int data:res) {
  72. cout << data << " ";
  73. }
  74. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
4 2 5 1 3