Advertisement
Guest User

Untitled

a guest
May 2nd, 2014
697
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. #ifndef BSTClass
  2. #define BSTClass
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. class BST
  8. {
  9. private:
  10. struct Node
  11. {
  12. string letter;
  13. string code;
  14. Node *left;
  15. Node *right;
  16. };
  17. Node *root;
  18.  
  19. public:
  20. BST()
  21. {
  22. root = NULL;
  23. }
  24. void Insert(Node *&r, string letter, string code)
  25. {
  26. if(r == NULL)
  27. {
  28. r = new Node; r->letter = letter;
  29. r->left = r->right = NULL; r->code = code;
  30. }
  31. if(r->letter > letter) Insert(r->left, letter, code);
  32. if(r->letter < letter) Insert(r->right, letter, code);
  33. }
  34. void Insert(string letter, string code){Insert(root, letter, code);}
  35. void DisplayPreOrder(Node *r)
  36. {
  37. if(r != NULL)
  38. {
  39. // (P)(LC)(RC)
  40. cout << r->letter << "\t";
  41. DisplayInOrder(r->left);
  42. DisplayInOrder(r->right);
  43. }
  44. }
  45. void DisplayInOrder(Node *r)
  46. {
  47. if(r != NULL)
  48. {
  49. // (LC)(P)(RC)
  50. DisplayInOrder(r->left);
  51. cout << r->letter << "\t";
  52. DisplayInOrder(r->right);
  53. }
  54. }
  55. // Overrides DisplayInOrder(Node * )
  56. void DisplayInOrder(){DisplayInOrder(root);}
  57. void DisplayPreOrder(){DisplayPreOrder(root);}
  58. void DisplayPostOrder(Node *r)
  59. {
  60. if(r != NULL)
  61. {
  62. // (LC)(P)(RC)
  63. DisplayPostOrder(r->left);
  64. DisplayPostOrder(r->right);
  65. cout << r->letter << "\t";
  66. }
  67. }
  68. void Encode(char x)
  69. {
  70. Node* r = SearchAndReturn(root, x);
  71. if(r != NULL) cout << r->code;
  72. else cout << "Error.";
  73. }
  74. void Decode(string x)
  75. {
  76. Node* r = SearchAndReturnString(root, x);
  77. if(r->code == x) cout << r->letter;
  78. else cout << r->code << " with x being " << x << endl; cout << "Error.";
  79. }
  80. Node* SearchAndReturn(Node *r, char x)
  81. {
  82. if(r != NULL)
  83. {
  84. if(r->letter[0] == x) {return r;}
  85. else if(r->letter[0] > x) {SearchAndReturn(r->left, x);}
  86. else {SearchAndReturn(r->right, x);}
  87. }
  88. else return NULL;
  89. }
  90. Node* SearchAndReturnString(Node *r, string x)
  91. {
  92. if(r != NULL)
  93. {
  94. if(r->code == x) {cout << r->code << " matches " << x << endl; return r;}
  95. else if(r->code > x) {SearchAndReturnString(r->left, x);}
  96. else {SearchAndReturnString(r->right, x);}
  97. }
  98. else return NULL;
  99. }
  100. };
  101. #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement