Advertisement
momo2345

BST

May 23rd, 2023
878
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.03 KB | None | 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. Node* createNode(int val) {
  11.     Node* newNode = new Node;
  12.     newNode->data = val;
  13.     newNode->left = nullptr;
  14.     newNode->right = nullptr;
  15.     return newNode;
  16. }
  17. Node* insert(Node* root, int val) {
  18.     if (root == nullptr) {
  19.         return createNode(val);
  20.     }
  21.  
  22.     if (val < root->data) {
  23.         root->left = insert(root->left, val);
  24.     } else {
  25.         root->right = insert(root->right, val);
  26.     }
  27.  
  28.     return root;
  29. }
  30.  
  31. void postorderTraversal(Node* root) {
  32.     if (root == nullptr) {
  33.         return;
  34.     }
  35.  
  36.     postorderTraversal(root->left);
  37.     postorderTraversal(root->right);
  38.     cout << root->data << endl;
  39. }
  40.  
  41. int main() {
  42.     Node* root = nullptr;
  43.     int val;
  44.     while(cin>>val){
  45.             if(root == nullptr) root = insert(root, val);
  46.             else insert(root, val);
  47.     }
  48.      postorderTraversal(root);
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement