Advertisement
CHU2

Second Largest Inorder Traversal

Mar 9th, 2023
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.63 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*, int&);
  22.  
  23. int main() {
  24.     int temp;
  25.     int h = 0;      //created h as a tally
  26.     queue<int> q;
  27.  
  28.     srand(time(NULL));
  29.  
  30.     for (int h = 0; h < 15; h++) {
  31.         temp = rand() % 99 + 1;     //limit random numbers from 1-99
  32.         q.push(temp);
  33.     }
  34.    
  35.     node* root = new node(q.front());
  36.     q.pop();
  37.  
  38.     while (!q.empty()) {
  39.         add(root, q.front());
  40.         q.pop();
  41.     }
  42.  
  43.     cout << " Random BST values in Inorder: ";
  44.     inorder(root);
  45.  
  46.     cout << "\n Second largest value is: ";
  47.     anotherinorder(root, h);
  48.    
  49.     return 0;
  50. }
  51.  
  52. node* add(node* root, int value) {
  53.     if (root == NULL) {
  54.         root = new node(value);
  55.     }
  56.     else if (value <= root->data) {
  57.         root->left = add(root->left, value);
  58.     }
  59.     else if (value > root->data) {
  60.         root->right = add(root->right, value);
  61.     }
  62.  
  63.     return root;
  64. }
  65.  
  66. void inorder(node* nnode) {
  67.     if (nnode == NULL) {
  68.         return;
  69.     }
  70.  
  71.     inorder(nnode->left);
  72.  
  73.     cout << nnode->data << ' ';
  74.  
  75.     inorder(nnode->right);
  76. }
  77.  
  78. void anotherinorder(node* nnode, int& h) {      //recursion seems to can't affect a referenced data so why not take advantage
  79.     if (nnode == NULL) {
  80.         return;
  81.     }
  82.  
  83.     h++;        //an increment in every recursion
  84.  
  85.     anotherinorder(nnode->left, h);
  86.  
  87.     if (h == 14) {      //another inorder function but can only cout value if it's second to the last which is the second highest in inorder traversal pattern
  88.         cout << nnode->data;
  89.     }
  90.  
  91.     anotherinorder(nnode->right, h);
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement