Guest User

Untitled

a guest
Oct 1st, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. # define ALPHABET_SIZE 26
  2. #include<iostream>
  3. using namespace std;
  4.  
  5. typedef struct node {
  6. node* children[ALPHABET_SIZE];
  7. bool isLeaf;
  8. };
  9.  
  10. node* newNode() {
  11. node* pNode = new node;
  12. pNode->isLeaf = false;
  13. for (int i = 0; i < ALPHABET_SIZE; i++)
  14. pNode->children[i] = nullptr;
  15.  
  16. return pNode;
  17. }
  18.  
  19. void insert(node* root, const char* str) {
  20. node* pCrawl = root;
  21.  
  22. while (*str) {
  23. int index = *str - 'a';
  24. if (!pCrawl->children[index])
  25. pCrawl->children[index] = newNode();
  26. pCrawl = pCrawl->children[index];
  27. str++;
  28. }
  29. pCrawl->isLeaf = true;
  30. }
  31.  
  32. bool search(node* root, const char* str) {
  33. node* pCrawl = root;
  34.  
  35. while (*str) {
  36. int index = *str - 'a';
  37. if (!pCrawl->children[index])
  38. return false;
  39. pCrawl = pCrawl->children[index];
  40. str++;
  41. }
  42.  
  43. return (pCrawl != nullptr && pCrawl->isLeaf);
  44. }
  45.  
  46. bool hasChildren(node* currNode) {
  47.  
  48. for (int i = 0; i < ALPHABET_SIZE; i++) {
  49. if (currNode->children[i] != nullptr) {
  50. return true;
  51. }
  52. }
  53.  
  54. return false;
  55. }
  56.  
  57. bool deleteKey(node* pNode, const char* str){
  58.  
  59. if (pNode == nullptr)
  60. return false;
  61. if (*str) {
  62. int index = *str - 'a';
  63. if (pNode != nullptr && pNode->children[index]
  64. && deleteKey(pNode->children[index], str + 1) && !pNode->isLeaf) {
  65.  
  66. if (!hasChildren) {
  67. delete pNode;
  68. pNode = nullptr;
  69. return true;
  70. }
  71. else {
  72. return false;
  73. }
  74. }
  75. }
  76.  
  77. if (*str == '\0' && pNode->isLeaf) {
  78. if (!hasChildren(pNode)) {
  79. delete pNode;
  80. pNode = nullptr;
  81. return true;
  82. }
  83. else {
  84. pNode->isLeaf = false;
  85. return false;
  86. }
  87. }
  88.  
  89. return false;
  90. }
  91.  
  92. int main()
  93. {
  94. const char* keys[] = { "the", "a", "there",
  95. "answer", "any", "by",
  96. "bye", "their" };
  97. int n = sizeof(keys) / sizeof(keys[0]);
  98.  
  99. node *root = newNode();
  100.  
  101. for (int i = 0; i < n; i++)
  102. insert(root, keys[i]);
  103.  
  104. search(root, "the") ? cout << "Yes\n" :
  105. cout << "No\n";
  106. search(root, "these") ? cout << "Yes\n" :
  107. cout << "No\n";
  108. cout << deleteKey(root, "the")<< endl;
  109. search(root, "the") ? cout << "Yes\n" :
  110. cout << "No\n";
  111. search(root, "there") ? cout << "Yes\n" :
  112. cout << "No\n";
  113. cout << deleteKey(root, "any") << endl;
  114. search(root, "any") ? cout << "Yes\n" :
  115. cout << "No\n";
  116.  
  117. }
Add Comment
Please, Sign In to add comment