Advertisement
CHU2

No Left Child Inorder Traversal

Mar 9th, 2023 (edited)
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.45 KB | Source Code | 0 0
  1. #include <iostream>
  2. #include <queue>
  3.  
  4. using namespace std;
  5.  
  6. class node {
  7. public:
  8.     int data;
  9.     node* left;
  10.     node* right;
  11.  
  12.     node(int value) {
  13.         data = value;
  14.         left = NULL;
  15.         right = NULL;
  16.     }
  17. };
  18.  
  19. node* add(node*, int);
  20. void inorder(node*);
  21. void anotherinorder(node*);
  22.  
  23. int main() {
  24.     int temp;
  25.     queue<int> q;
  26.  
  27.     srand(time(NULL));
  28.  
  29.     for (int h = 0; h < 15; h++) {
  30.         temp = rand() % 99 + 1;     //limit random numbers from 1-99
  31.         q.push(temp);       //store on queue to use later
  32.     }
  33.  
  34.     node* root = new node(q.front());
  35.     q.pop();
  36.  
  37.     while (!q.empty()) {
  38.         add(root, q.front());
  39.         q.pop();
  40.     }
  41.  
  42.     cout << " Random BST values in Inorder: ";
  43.     inorder(root);
  44.  
  45.     cout << "\n Nodes that has no Left child valuea are: ";
  46.     anotherinorder(root);
  47.  
  48.     return 0;
  49. }
  50.  
  51. node* add(node* root, int value) {
  52.     if (root == NULL) {
  53.         root = new node(value);
  54.     }
  55.     else if (value <= root->data) {
  56.         root->left = add(root->left, value);
  57.     }
  58.     else if (value > root->data) {
  59.         root->right = add(root->right, value);
  60.     }
  61.  
  62.     return root;
  63. }
  64.  
  65. void inorder(node* nnode) {
  66.     if (nnode == NULL) {
  67.         return;
  68.     }
  69.  
  70.     inorder(nnode->left);
  71.  
  72.     cout << nnode->data << ' ';
  73.  
  74.     inorder(nnode->right);
  75. }
  76.  
  77. void anotherinorder(node* nnode) {
  78.     if (nnode == NULL) {
  79.         return;
  80.     }
  81.  
  82.     anotherinorder(nnode->left);
  83.  
  84.     if (nnode->left == NULL) {      //another inorder function but has the cout-if-left-is-null proccess
  85.         cout << nnode->data << ' ';
  86.     }
  87.  
  88.     anotherinorder(nnode->right);
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement