Guest User

Untitled

a guest
May 5th, 2017
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. #include "Tree.h"
  2. #include<iostream>
  3. #include<fstream>
  4.  
  5. using namespace std;
  6.  
  7. BinaryTree::BinaryTree()
  8. {
  9.     root = nullptr;
  10. }
  11.  
  12. BinaryTree:: ~BinaryTree()
  13. {
  14.     cout << "Clear Binary Tree" << endl;
  15.     Clear(root);
  16. }
  17.  
  18. void BinaryTree::Clear(node* nod)
  19. {
  20.     if (nod != nullptr)
  21.     {
  22.         Clear(nod->left);
  23.         Clear(nod->right);
  24.         cout <<"Deleting node: " <<nod->key << endl;
  25.         delete nod;
  26.     }
  27. }
  28.  
  29. void BinaryTree::Insert(int x)
  30. {
  31.     Insert(x, root);
  32. }
  33.  
  34. void BinaryTree::Insert(int x, node*& nod)
  35. {
  36.     if (nod == nullptr)
  37.     {
  38.         nod = new node();
  39.         nod->left = nullptr;
  40.         nod->right = nullptr;
  41.         nod->key = x;
  42.     }
  43.     else
  44.         if (x<nod->key)
  45.             Insert(x, nod->left);
  46.         else
  47.             if (x>nod->key)
  48.                 Insert(x, nod->right);
  49. }
  50.  
  51. bool BinaryTree::Search(int x)
  52. {
  53.     return Search(x, root);
  54. }
  55.  
  56. void BinaryTree::treeToFile(ofstream & file)
  57. {
  58.     return treeToFile(root, file);
  59. }
  60.  
  61. bool BinaryTree::Search(int x, node* nod)
  62. {
  63.     if (nod == nullptr)
  64.         return false;
  65.  
  66.     if (nod->key == x)
  67.         return true;
  68.  
  69.     if (x<nod->key)
  70.         Search(x, nod->left);
  71.     else
  72.         if (x>nod->key)
  73.             Search(x, nod->right);
  74. }
  75.  
  76. void BinaryTree::InOrder()
  77. {
  78.     cout << "Inorder traversal:" << endl;
  79.     InOrder(root);
  80. }
  81.  
  82. void BinaryTree::InOrder(node* nod)
  83. {
  84.     if (nod != nullptr)
  85.     {
  86.         InOrder(nod->left);
  87.         cout <<"Node with key: "<<nod->key <<endl;
  88.         InOrder(nod->right);
  89.     }
  90. }
  91. void BinaryTree::treeToFile(node* root, ofstream& file)
  92. {  
  93.     if (!file.is_open()){
  94.         cout << "File cannot be opened" << endl;
  95.     }
  96.     if (root == NULL) {
  97.         file << "#" << ";";
  98.         return;
  99.     }
  100.     file << root->key << ';';
  101.     treeToFile(root->left, file);
  102.     treeToFile(root->right, file);
  103.     file.close();
  104.    
  105. }
Add Comment
Please, Sign In to add comment