Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <iomanip>
- using namespace std;
- class Node;
- typedef Node* NodePtr;
- class Node
- {
- public:
- int data;
- NodePtr left;
- NodePtr right;
- Node() : data(0), left(NULL), right(NULL) {}
- };
- class BST
- {
- private:
- NodePtr root;
- public:
- BST() : root(NULL){}
- void Insert(int num)
- {
- Insert( num, root );
- }
- void Insert(int num, NodePtr& node)
- {
- if(node == NULL)
- {
- node = new Node();
- node->data = num;
- }
- else if(num < node->data)
- {
- Insert(num, node->left);
- }
- else if(num > node->data)
- {
- Insert(num, node->right);
- }
- else
- {
- cout << " Node value " << node->data << " already exists.";
- cout << endl;
- }
- }
- void PrintTree(ostream& output, NodePtr& node, int indent)
- {
- if(node!=NULL)
- {
- PrintTree(output, node->right, indent+8 );
- output << setw(indent) << node->data << endl;
- PrintTree(output, node->left, indent + 8);
- }
- }
- friend ostream& operator<<(ostream &output, BST& bst);
- };
- ostream& operator<<(ostream &output, BST& bst)
- {
- bst.PrintTree(output, bst.root, 0);
- return output;
- }
- int main()
- {
- BST bst;
- bst.Insert( 5 );
- bst.Insert( 3 );
- bst.Insert( 7 );
- bst.Insert( 2 );
- bst.Insert( 4 );
- bst.Insert( 6 );
- bst.Insert( 8 );
- cout << bst << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement