Advertisement
Guest User

Untitled

a guest
Nov 19th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.71 KB | None | 0 0
  1.  
  2. // task 1
  3. BST(){
  4. root = NULL;
  5. }
  6. void insert(int value){
  7. root = insert(root, value);
  8. }
  9.  
  10. void realPrint(Node* root, int dividedBy)
  11. {
  12. if(root == nullptr)
  13. return;
  14.  
  15. bool isLeaf = root->left || root->right;
  16. if(root->value % dividedBy == 0 && isLeaf)
  17. {
  18. cout << root->value << " ";
  19. }
  20. realPrint(root->left, dividedBy);
  21. realPrint(root->right, dividedBy);
  22. }
  23.  
  24. void printSpecific(int dividedBy) {
  25. realPrint(root, dividedBy);
  26. }
  27.  
  28. // task 2
  29.  
  30. BST() {
  31. root = NULL;
  32. }
  33.  
  34. void insert(int value) {
  35. root = insert(root, value);
  36. }
  37.  
  38. void realPrint(Node* root, int k, int currDist)
  39. {
  40. if(root == nullptr)
  41. return;
  42.  
  43. realPrint(root->right, k, currDist + 1);
  44. if(currDist == k)
  45. {
  46. cout << root->value << " ";
  47. }
  48. realPrint(root->left, k, currDist + 1);
  49.  
  50. }
  51.  
  52. void printKDistant(int k) {
  53. realPrint(root, k, 0);
  54. }
  55.  
  56. // task 3
  57. struct Node {
  58. Node *left;
  59. Node *right;
  60. int value;
  61. bool isLeaf;
  62.  
  63. Node(int value) {
  64. this->value = value;
  65. this->left = NULL;
  66. this->right = NULL;
  67. }
  68. };
  69.  
  70. class BST {
  71.  
  72. public:
  73. BST() {
  74. root = NULL;
  75. }
  76.  
  77. void insert(int value) {
  78. root = insert(root, value);
  79. }
  80.  
  81. void leafs(Node* root)
  82. {
  83. if(root == nullptr)
  84. {
  85. return;
  86. }
  87.  
  88. leafs(root->left);
  89. if(root->left == nullptr && root->right == nullptr)
  90. {
  91. root->isLeaf = true;
  92. }
  93. else
  94. root->isLeaf = false;
  95.  
  96. leafs(root->right);
  97.  
  98.  
  99. }
  100.  
  101. void mydelete(Node* root)
  102. {
  103. if(root == nullptr)
  104. {
  105. return;
  106. }
  107.  
  108. mydelete(root->left);
  109.  
  110. bool toBeDeleted1 = false;
  111. bool toBeDeleted2 = false;
  112. bool toBeDeleted3 = false;
  113.  
  114. if(root->left && root->right)
  115. toBeDeleted1 = root->left->isLeaf && root->right->isLeaf;
  116. if(root->left)
  117. toBeDeleted2 = root->left->isLeaf && root->right == nullptr;
  118. if(root->right)
  119. toBeDeleted3 = root->left == nullptr && root->right->isLeaf;
  120.  
  121. bool del = toBeDeleted1 || toBeDeleted2 || toBeDeleted3;
  122.  
  123. if(!del)
  124. cout << root->value << " ";
  125.  
  126. mydelete(root->right);
  127.  
  128. }
  129.  
  130. void deletePenultimateAndPrint() {
  131. leafs(root);
  132. mydelete(root);
  133. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement