Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "Tree.h"
- #include<iostream>
- #include<fstream>
- using namespace std;
- BinaryTree::BinaryTree()
- {
- root = nullptr;
- }
- BinaryTree:: ~BinaryTree()
- {
- cout << "Clear Binary Tree" << endl;
- Clear(root);
- }
- void BinaryTree::Clear(node* nod)
- {
- if (nod != nullptr)
- {
- Clear(nod->left);
- Clear(nod->right);
- cout <<"Deleting node: " <<nod->key << endl;
- delete nod;
- }
- }
- void BinaryTree::Insert(int x)
- {
- Insert(x, root);
- }
- void BinaryTree::Insert(int x, node*& nod)
- {
- if (nod == nullptr)
- {
- nod = new node();
- nod->left = nullptr;
- nod->right = nullptr;
- nod->key = x;
- }
- else
- if (x<nod->key)
- Insert(x, nod->left);
- else
- if (x>nod->key)
- Insert(x, nod->right);
- }
- bool BinaryTree::Search(int x)
- {
- return Search(x, root);
- }
- void BinaryTree::treeToFile(ofstream & file)
- {
- return treeToFile(root, file);
- }
- bool BinaryTree::Search(int x, node* nod)
- {
- if (nod == nullptr)
- return false;
- if (nod->key == x)
- return true;
- if (x<nod->key)
- Search(x, nod->left);
- else
- if (x>nod->key)
- Search(x, nod->right);
- }
- void BinaryTree::InOrder()
- {
- cout << "Inorder traversal:" << endl;
- InOrder(root);
- }
- void BinaryTree::InOrder(node* nod)
- {
- if (nod != nullptr)
- {
- InOrder(nod->left);
- cout <<"Node with key: "<<nod->key <<endl;
- InOrder(nod->right);
- }
- }
- void BinaryTree::treeToFile(node* root, ofstream& file)
- {
- if (!file.is_open()){
- cout << "File cannot be opened" << endl;
- }
- if (root == NULL) {
- file << "#" << ";";
- return;
- }
- file << root->key << ';';
- treeToFile(root->left, file);
- treeToFile(root->right, file);
- file.close();
- }
Add Comment
Please, Sign In to add comment