enkacang

PBE2 - d) FULL CODE

Aug 24th, 2021 (edited)
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.16 KB | None | 0 0
  1. // PBE2 - MUHAMMAD HILMI/DAVINUS
  2.  
  3. #include <iostream>
  4. using namespace std;
  5.  
  6. int numRightNode{ 0 };
  7. int numLeftNode{ 0 };
  8.  
  9. // a) data structure for BST
  10. struct node {
  11.     int root;
  12.     struct node* left;
  13.     struct node* right;
  14. };
  15.  
  16. struct node* newNode(int item) {
  17.     struct node* temp = new node;
  18.     temp->root = item;
  19.     temp->left = temp->right = NULL;
  20.     return temp;
  21. }
  22.  
  23. bool countNodes(struct node* root, string direction) {
  24.  
  25.     //c) to clarify if root is empty then return false
  26.     //d) if not null the funtion will loop on itself
  27.     //   due to condition that it will find their matches
  28.     //   every time they find it, if statement will be fire up
  29.     //   depends on if statement of
  30.     //   this countnode function arguments
  31.     //   by that means, if the function loop is on left
  32.     //   if statement will compare left one and if it's true
  33.     //   numLeftNode will be incremented by 1
  34.     //   lastly this value will be printed in main() function
  35.  
  36.  
  37.     if (root != NULL) {
  38.         countNodes(root->left, "left");
  39.  
  40.         if (direction == "left") numLeftNode++;
  41.         if (direction == "right") numRightNode++;
  42.  
  43.         countNodes(root->right, "right");
  44.     }
  45.     else
  46.     {
  47.         return false;
  48.     }
  49.  
  50.     return true;
  51. }
  52.  
  53. struct node* insert(struct node* node, int val) {
  54.  
  55.     if (node == NULL) return newNode(val);
  56.  
  57.     if (val < node->root)
  58.         node->left = insert(node->left, val);
  59.    
  60.     if(val > node->root)
  61.         node->right = insert(node->right, val);
  62.  
  63.     return node;
  64. }
  65.  
  66. int main() {
  67.     //b) function create new BST
  68.     struct node* root = NULL;
  69.  
  70.     root = insert(root, 10);
  71.     root = insert(root, 23);
  72.     root = insert(root, 9);
  73.     root = insert(root, 2);
  74.     root = insert(root, 22);
  75.     root = insert(root, 34);
  76.  
  77.     // d.1) it will detect true or false if false node will be 0;
  78.     if (!countNodes(root, "NULL"))
  79.     {
  80.         cout << "Node is 0";
  81.  
  82.         return 0;
  83.     }
  84.  
  85.     cout << "Left Node :" << numLeftNode;
  86.     cout << endl;
  87.     cout << "Right Node :" << numRightNode;
  88.     cout << endl; cout << endl;
  89.  
  90.     cout << "total Node :" << numLeftNode + numRightNode + 1;
  91. }
Add Comment
Please, Sign In to add comment