Advertisement
Guest User

Untitled

a guest
Jul 20th, 2017
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3.  
  4. using namespace std;
  5. class Node;
  6.  
  7. typedef Node* NodePtr;
  8. class Node
  9. {
  10.  
  11. public:
  12.     int data;
  13.     NodePtr left;
  14.     NodePtr right;
  15.  
  16.     Node() : data(0), left(NULL), right(NULL) {}
  17.  
  18.  
  19. };
  20.  
  21. class BST
  22. {
  23. private:
  24.     NodePtr root;
  25.  
  26. public:
  27.     BST() : root(NULL){}
  28.  
  29.     void Insert(int num)
  30.     {
  31.         Insert( num, root );
  32.     }
  33.  
  34.     void Insert(int num, NodePtr& node)
  35.     {
  36.         if(node == NULL)
  37.         {
  38.             node = new Node();
  39.             node->data = num;
  40.         }
  41.         else if(num < node->data)
  42.         {
  43.             Insert(num, node->left);
  44.         }
  45.         else if(num > node->data)
  46.         {
  47.             Insert(num, node->right);
  48.         }
  49.         else
  50.         {
  51.             cout << " Node value " << node->data << " already exists.";
  52.             cout << endl;
  53.         }
  54.     }
  55.  
  56.     void PrintTree(ostream& output, NodePtr& node, int indent)
  57.     {
  58.         if(node!=NULL)
  59.         {
  60.             PrintTree(output, node->right, indent+8 );
  61.             output << setw(indent) << node->data << endl;
  62.             PrintTree(output, node->left, indent + 8);
  63.         }
  64.     }
  65.     friend ostream& operator<<(ostream &output, BST& bst);
  66. };
  67.  
  68.  ostream& operator<<(ostream &output, BST& bst)
  69.  {
  70.      bst.PrintTree(output, bst.root, 0);
  71.  
  72.      return output;
  73.  }
  74.  
  75. int main()
  76. {
  77.  
  78.     BST bst;
  79.  
  80.     bst.Insert( 5 );
  81.     bst.Insert( 3 );
  82.     bst.Insert( 7 );
  83.     bst.Insert( 2 );
  84.     bst.Insert( 4 );
  85.     bst.Insert( 6 );
  86.     bst.Insert( 8 );
  87.  
  88.     cout << bst << endl;
  89.     return 0;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement