Naxocist

TA12_ARMY

Apr 9th, 2022
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4.  
  5. struct node{
  6.     int val;
  7.     node *left, *right;
  8. };
  9.  
  10.  
  11. node *createNode(double data){
  12.     node *newNode = new node;
  13.     newNode->val = data;
  14.     newNode->left = NULL;
  15.     newNode->right = NULL;
  16.  
  17.     return newNode;
  18. }
  19.  
  20. node *insertBST(node *root, int data){
  21.     if(root == NULL) return createNode(data);
  22.  
  23.     if(data < root->val){
  24.         root->left = insertBST(root->left, data);
  25.     }else{
  26.         root->right = insertBST(root->right, data);
  27.     }
  28.  
  29.     return root;
  30. }
  31.  
  32. void inOrder(node *root){
  33.     if(root == NULL) return ;
  34.  
  35.     inOrder(root->left);
  36.     printf("%d ", root->val);
  37.     inOrder(root->right);
  38. }
  39.  
  40.  
  41. int main(){
  42.  
  43.     int n, x; scanf("%d", &n);
  44.  
  45.     node *root = NULL;
  46.     while(n--){
  47.         scanf("%d", &x);
  48.  
  49.         root = insertBST(root, x);
  50.     }
  51.     if(root == NULL) {
  52.         return 0;
  53.     }
  54.  
  55.     queue<node*> q;
  56.     q.push(root);
  57.     while(!q.empty()){
  58.         int s = q.size();
  59.  
  60.         for(int i=0; i<s; ++i){
  61.  
  62.             node *N = q.front();
  63.             q.pop();
  64.             if(i==0 || i == s-1){
  65.                 printf("%d ", N->val);
  66.             }
  67.  
  68.             if(N->left != NULL) q.push(N->left);
  69.             if(N->right != NULL) q.push(N->right);
  70.         }  
  71.  
  72.         printf("\n");
  73.     }
  74.     // inOrder(root);
  75.     return 0;
  76. }
  77.  
Advertisement
Add Comment
Please, Sign In to add comment