fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct node {
  5. string code;
  6. node *left, *right;
  7. };
  8. class BST {
  9. node *root=nullptr;
  10. public:
  11. void Insert(node *&start, string key);
  12. void Insert(string key);
  13. void show(node *start=nullptr, int level=0, string t="") {
  14. if (start) {
  15. if (start->left)
  16. show (start->left, level+1, "L:");
  17. else cout << string((level+1)*2,' ') <<"LX"<<endl;
  18. cout << string(level*2,' ') <<t << start->code <<endl;
  19. if (start->right)
  20. show (start->right, level+1, "R:");
  21. else cout << string((level+1)*2,' ') <<"RX"<<endl;
  22. }
  23. else show(root);
  24. }
  25. };
  26.  
  27. void BST::Insert(node *&start, string key){
  28. if (start == NULL) {
  29. start = new node;
  30. start->code = key;
  31. start->left = start->right = NULL;
  32. printf("Inserting Morse Code -> %s\n",key.c_str());
  33. }
  34. else if (start->code<key)
  35. Insert (start->left, key);
  36. else if (start->code>key)
  37. Insert (start->right, key);
  38. else cout<<"Duplicate"<<endl;
  39. }
  40.  
  41. void BST::Insert(string key) {
  42. Insert(root, key);
  43. /*
  44.   node **start = &root;
  45.   if (*start != NULL) {
  46.   if (start->code<key)
  47.   for(int i = 0; i < key.length(); i++) {
  48.   if (key[i] == '.') {
  49.   start = &((*start)->left);
  50.   } else if (key[i] == '-') {
  51.   start = &((*start)->right);
  52.   }else {
  53.   break;
  54.   }
  55.   Insert(*start, key);
  56.   }
  57.   } else {
  58.   Insert(root, key);
  59.   }*/
  60. }
  61.  
  62. int main() {
  63. BST b;
  64. b.Insert(".-");
  65. b.Insert("-...");
  66. b.Insert("-.-.");
  67. b.Insert(".");
  68. b.show();
  69. return 0;
  70. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Inserting Morse Code -> .-
Inserting Morse Code -> -...
Inserting Morse Code -> -.-.
Inserting Morse Code -> .
  LX
.-
      LX
    L:.
      RX
  R:-...
      LX
    R:-.-.
      RX