sahadat49

BST

Dec 5th, 2018
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3. struct node{
  4. int val;
  5. node *left;
  6. node *right;
  7. node(){
  8. val=0;
  9. left=right=NULL;
  10. }
  11. };
  12. class BST{
  13. private: node *ROOT;
  14. public:
  15. BST();
  16. void insert1(int x);
  17. void insert2(node *r,int x);
  18. void print();
  19. };
  20.  
  21. BST::BST(){
  22. ROOT=NULL;
  23. }
  24. void BST::insert1(int x)
  25. {
  26. insert2(ROOT,x);
  27. }
  28. void BST::insert2(node *r,int x)
  29. {
  30. if(r==NULL){
  31. node *n=new node();
  32. n->val=x;
  33. ROOT=n;
  34. return;
  35. }
  36. if(x<=r->val){
  37. if(r->left==NULL){
  38. node *n=new node();
  39. n->val=x;
  40. r->left=n;
  41. return;
  42.  
  43. }
  44. else {
  45. insert2(r->left,x);
  46. return;
  47. }
  48. }
  49. else{
  50. if(r->right==NULL){
  51. node *n=new node();
  52. n->val=x;
  53. r->right=n;
  54. return;
  55. }
  56. else{
  57. insert2(r->right,x);
  58. return;
  59. }
  60. }
  61. }
  62. void BST::print(){
  63. node *cur=ROOT;
  64. while(cur!=NULL){
  65. cout<<cur->val<<" ";
  66. cur=cur->left;
  67. }
  68. }
  69. int main()
  70. {
  71. BST *m=new BST();
  72. m->insert1(4);
  73. m->insert1(2);
  74. m->insert1(1);
  75. m->insert1(5);
  76. m->insert1(6);
  77. m->insert1(9);
  78. m->insert1(0);
  79. m->print();
  80. }
Advertisement
Add Comment
Please, Sign In to add comment