Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // PBE2 - MUHAMMAD HILMI/DAVINUS
- #include <iostream>
- using namespace std;
- int numRightNode{ 0 };
- int numLeftNode{ 0 };
- // a) data structure for BST
- struct node {
- int root;
- struct node* left;
- struct node* right;
- };
- struct node* newNode(int item) {
- struct node* temp = new node;
- temp->root = item;
- temp->left = temp->right = NULL;
- return temp;
- }
- bool countNodes(struct node* root, string direction) {
- //c) to clarify if root is empty then return false
- //d) if not null the funtion will loop on itself
- // due to condition that it will find their matches
- // every time they find it, if statement will be fire up
- // depends on if statement of
- // this countnode function arguments
- // by that means, if the function loop is on left
- // if statement will compare left one and if it's true
- // numLeftNode will be incremented by 1
- // lastly this value will be printed in main() function
- if (root != NULL) {
- countNodes(root->left, "left");
- if (direction == "left") numLeftNode++;
- if (direction == "right") numRightNode++;
- countNodes(root->right, "right");
- }
- else
- {
- return false;
- }
- return true;
- }
- struct node* insert(struct node* node, int val) {
- if (node == NULL) return newNode(val);
- if (val < node->root)
- node->left = insert(node->left, val);
- if(val > node->root)
- node->right = insert(node->right, val);
- return node;
- }
- int main() {
- //b) function create new BST
- struct node* root = NULL;
- root = insert(root, 10);
- root = insert(root, 23);
- root = insert(root, 9);
- root = insert(root, 2);
- root = insert(root, 22);
- root = insert(root, 34);
- // d.1) it will detect true or false if false node will be 0;
- if (!countNodes(root, "NULL"))
- {
- cout << "Node is 0";
- return 0;
- }
- cout << "Left Node :" << numLeftNode;
- cout << endl;
- cout << "Right Node :" << numRightNode;
- cout << endl; cout << endl;
- cout << "total Node :" << numLeftNode + numRightNode + 1;
- }
Add Comment
Please, Sign In to add comment