Advertisement
vaibhav1906

BST Implementation

Jan 4th, 2022
1,169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct treeNode{
  5.     int val;
  6.     treeNode * left;
  7.     treeNode * right;
  8. };
  9.  
  10. treeNode * addNode(treeNode * root, int data){
  11.     if(root==NULL){
  12.         treeNode * a = new treeNode();
  13.         a->val = data;
  14.         a->left = NULL;
  15.         a->right = NULL;
  16.         root = a;
  17.     }
  18.     else{
  19.        
  20.         if(root->val > data){
  21.             root->left = addNode(root->left, data);
  22.         }
  23.         else{
  24.             root->right = addNode(root->right, data);
  25.         }
  26.        
  27.     }
  28.    
  29.     return root;
  30. }
  31.  
  32. void print(treeNode * root){
  33.     if(root==NULL)return;
  34.    
  35.     cout<<root->val<<" ";
  36.     print(root->left);
  37.     print(root->right);
  38.    
  39. }
  40.  
  41. void levelOrder(treeNode * root){
  42.    
  43.     queue<treeNode*> q;
  44.     q.push(root);
  45.    
  46.     while(q.size()!=0){
  47.         treeNode * temp = q.front();
  48.        
  49.         cout<<temp->val<<" ";
  50.         q.pop();
  51.        
  52.         if(temp->left!=NULL){
  53.             q.push(temp->left);
  54.         }
  55.         if(temp->right!=NULL){
  56.             q.push(temp->right);
  57.         }
  58.        
  59.     }
  60.    
  61.    
  62. }
  63.  
  64. int main(){
  65.    
  66.     int n;
  67.     cout<<"Total num of nodes in tree you want"<<endl;
  68.     cin>>n;
  69.    
  70.     treeNode * root = NULL;
  71.    
  72.     for(int i = 0; i<n; i++){
  73.         int data;
  74.         cout<<"Enter an integer : "<<endl;
  75.         cin>>data;
  76.         root = addNode(root, data);
  77.        
  78.     }
  79.    
  80.     print(root); //preorder
  81.     cout<<endl;
  82.     levelOrder(root); //levelorder
  83. }
  84.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement