Advertisement
vaibhav1906

BST

Jul 17th, 2021
361
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct tree{
  5. int val;
  6. tree * left;
  7. tree * right;
  8. };
  9.  
  10. tree * addNode(tree* root, int x){
  11. if(root==NULL){
  12. tree * a = new tree();
  13. a->left = NULL;
  14. a->right = NULL;
  15. a->val = x;
  16. root = a;
  17. return root;
  18. }
  19. if(root->val<x){
  20. root->right = addNode(root->right,x);
  21. }
  22. else{
  23. root->left = addNode(root->left,x);
  24. }
  25.  
  26. return root;
  27. }
  28.  
  29. void inorder(tree * root){
  30. if(root == NULL)return;
  31.  
  32. inorder(root->left);
  33. cout<<root->val<<" ";
  34. inorder(root->right);
  35.  
  36.  
  37. }
  38.  
  39. int main(){
  40. int n;
  41. cout<<"Size of tree : \n";
  42. cin>>n;
  43. tree * root = NULL;
  44. for(int i=0; i<n; i++){
  45. int x;
  46. cin>>x;
  47. root = addNode(root,x);
  48. }
  49. cout<<"Printed Values : \n";
  50. inorder(root);
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement