Advertisement
momo2345

Untitled

May 23rd, 2023
770
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | Source Code | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. #define optimise ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
  4.  
  5. struct Node {
  6.     int data;
  7.     Node* left;
  8.     Node* right;
  9. };
  10.  
  11. Node* createNode(int val) {
  12.     Node* newNode = new Node;
  13.     newNode->data = val;
  14.     newNode->left = nullptr;
  15.     newNode->right = nullptr;
  16.     return newNode;
  17. }
  18.  
  19. Node* insert(Node* root, int val) {
  20.     if (root == nullptr) {
  21.         return createNode(val);
  22.     }
  23.  
  24.     if (val < root->data) {
  25.         root->left = insert(root->left, val);
  26.     } else {
  27.         root->right = insert(root->right, val);
  28.     }
  29.  
  30.     return root;
  31. }
  32.  
  33. void inorderTraversal(Node* root) {
  34.     if (root == nullptr) {
  35.         return;
  36.     }
  37.  
  38.     inorderTraversal(root->left);
  39.     inorderTraversal(root->right);
  40.     cout << root->data << endl;
  41. }
  42.  
  43. int main() {
  44.     Node* root = nullptr;
  45.     int val;
  46.     while(1){
  47.             cin>>val;
  48.             if(val == 0) break;
  49.             if(root == nullptr) root = insert(root, val);
  50.             else insert(root, val);
  51.     }
  52.      inorderTraversal(root);
  53. }
  54.  
  55.  
Tags: BST
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement