Advertisement
TShiva

tree

Jan 5th, 2015
369
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 6.41 KB | None | 0 0
  1. #include<istream>
  2. #include<fstream>
  3. #include <string>  
  4. #include<iostream>
  5. #include <sstream>  
  6. using namespace std;
  7.  
  8. /*Горбунов Никита мас-301
  9.  45 Написать набор функций, позволяющих работать с бинарным деревом
  10.    вещественных чисел:
  11.  
  12.    а. Ввести дерево из файла. Формат ввода: в каждой строке файла - одно
  13.       число, перед которым могут стоять символы табуляции. Пусть в какой-то
  14.       строке стоит число n в позиции k. Тогда потомки числа n стоят в
  15.       последующих строках в позиции (k+1). Пример. Следующий файл:
  16.  
  17. 5
  18.         6
  19.                 7
  20.                 8
  21.                         -10
  22.                         -5
  23.         9
  24.                 11
  25.                 13
  26.  
  27. кодирует дерево
  28.                       5
  29.                    /     \
  30.          /     \
  31.         6       9
  32.              /    \        /  \
  33.             7      8     11    13
  34.                  /   \
  35.               -10    -5
  36.  
  37.    б. Посчитать высоту и количество элементов в дереве
  38.    в. Напечатать путь от корня дерева до заданного элемента
  39.    г. Напечатать элементы дерева заданного уровня (уровень 0 -- корень
  40. дерева, уровень 1 -- потомки корня и т.п.)
  41.  
  42.  
  43.  
  44. */
  45.  
  46. struct TreeElem
  47. {
  48.     double info; //info - Число, которое я буду записывать в дерево
  49.     TreeElem *left, *right; //Адресные поля. Адрес левой части и Адрес правой части
  50. };
  51.  
  52. void PrintTree(TreeElem *root) //Функция обхода
  53. {
  54.     if (root) //Пока не встретится пустое звено
  55.     {
  56.         cout << root->info << " "; //Отображаем корень дерева
  57.         PrintTree(root->left); //Рекурсивная функция для вывода левого поддерева
  58.         PrintTree(root->right); //Рекурсивная функци для вывода правого поддерева
  59.     }
  60. }
  61.  
  62. void AddElem(TreeElem *&root, int i) //Функция добавления звена в дерево
  63. {
  64.     if (!root)
  65.     {
  66.         root = new TreeElem; //Выделяем память под звено дерева
  67.         root->info = i; //Записываем данные в звено
  68.         root->left = root->right = 0; //Подзвенья инициализируем пустотой во избежание ошибок
  69.         return;
  70.     }
  71.     if (i<root->info) AddElem(root->left, i);
  72.     if (i>root->info) AddElem(root->right, i);
  73.     else return;
  74. }
  75.  
  76. void DelTree(TreeElem*& root){
  77.     if (!root)
  78.         return;
  79.     DelTree(root->left);
  80.     DelTree(root->right);
  81.     delete root;
  82.     root=0;
  83. }
  84.  
  85.  
  86. TreeElem* Make(istream& in, int curspaces, string& str){
  87.  
  88.  
  89.  
  90.     TreeElem* root = 0;
  91.     root = new TreeElem;
  92.  
  93.     std::stringstream ss;
  94.     ss << str;
  95.     ss >> root->info;
  96.  
  97.     root->left = 0;
  98.     root->right = 0;
  99.  
  100.     getline(in, str);
  101.     int count = 0;
  102.     char a = str[0];
  103.     for (int i = 0; i<str.length() && str[i] == ' '; ++i){
  104.         count++;
  105.     }
  106.  
  107.     if (count > curspaces){
  108.         root->left = Make(in, count, str);
  109.         int count2 = 0;
  110.         for (int i = 0; i<str.length() && str[i] == ' '; ++i){
  111.             count2++;
  112.         }
  113.         if (count2 > curspaces){
  114.             root->right = Make(in, count, str);
  115.  
  116.         }
  117.         return root;
  118.     }
  119.     else if (count == curspaces){
  120.         return root;
  121.     }
  122.     else {//count < spaces
  123.         return root;
  124.     }
  125.  
  126.  
  127. }
  128.  
  129.  
  130.  
  131. TreeElem* MakeTreeFromFile(string FileName){
  132.     ifstream name(FileName.c_str());
  133.     TreeElem* root = 0;
  134.  
  135.  
  136.     string str = "";
  137.     getline(name, str);
  138.     int count = 0;
  139.     for (int i = 0; i<str.length() && str[i] == ' '; ++i){
  140.         count++;
  141.     }
  142.     root = Make(name, count, str);
  143.     return root;
  144. }
  145.  
  146. int NodeCount(TreeElem * root)
  147. {
  148.     if (root->left == 0 && root->right == 0)
  149.         return 1;
  150.     int l, r;
  151.     if (root->left != 0)
  152.         l = NodeCount(root->left);
  153.     else
  154.         l = 0;
  155.     if (root->right != 0)
  156.         r = NodeCount(root->right);
  157.     else
  158.         r = 0;
  159.  
  160.     return l+r+1;
  161. }
  162.  
  163. int HeightOfTree(TreeElem * root)
  164. {
  165.     if(root == 0)
  166.         return 0;
  167.     int l, r;
  168.     if (root->left != 0) {
  169.         l = HeightOfTree(root->left);
  170.     }else
  171.         l = -1;
  172.     if (root->right != 0) {
  173.         r = HeightOfTree(root->right);
  174.     }else
  175.         r = -1;
  176.     int max = l > r ? l : r;
  177.     return max+1;
  178.  
  179. }
  180.  
  181.  
  182.  
  183.  
  184. void PrintTreeLvl(TreeElem *root,int level){
  185.     if(root==0) return;
  186.     if (level == 0)
  187.     {
  188.         cout << root->info << " ";
  189.     }
  190.         PrintTreeLvl(root->left,level-1);
  191.         PrintTreeLvl(root->right,level-1 );
  192.        
  193. }
  194.  
  195.  
  196.  
  197. bool Search(TreeElem* root, double& x){
  198.     if (!root) return false;
  199.     if (abs(root->info - x) < 0.00001) return true;
  200.     bool a1,a2;
  201.     if (root->left) a1=Search(root->left, x); else a1 = false;
  202.     if (root->right) a2=Search(root->right, x); else a2 = false;
  203.     if (a1 || a2) return true;
  204.     else return false;
  205. }
  206.  
  207. bool SearchWaySub(TreeElem* root, double& x){
  208.     if (!root) return false;
  209.     if (abs(root->info - x) < 0.00001) return true;
  210.     bool a1,a2;
  211.     if (root->left) a1=SearchWaySub(root->left, x); else a1 = false;
  212.     if (root->right) a2=SearchWaySub(root->right, x); else a2 = false;
  213.     if (a1 || a2){
  214.         if (a1) cout << root->left->info << " ";
  215.         else cout << root->right->info << " ";
  216.         return true;
  217.     }
  218.     else return false;
  219. }
  220.  
  221. void SearchWay(TreeElem* root, double& x){
  222.     if (!root){
  223.         cout << "Tree is empty.";
  224.         return;
  225.     }
  226.     SearchWaySub(root,x);
  227.     cout << root->info << endl;
  228. }
  229.  
  230.  
  231.  
  232.  
  233.  
  234.  
  235.  
  236.  
  237. int main(int argc, char** argv) {
  238.  
  239.     string FileName = "C:\\ccc\\1.txt";
  240.     TreeElem *Tree = 0;
  241.     Tree = MakeTreeFromFile(FileName);
  242.     PrintTree(Tree); //Вызов функции обхода дерева;  
  243.         int count = NodeCount(Tree);
  244.         cout<<"The number of nodes " << count<<endl;
  245.         int hght = HeightOfTree(Tree);
  246.         cout <<"Height of Tree " << hght<<endl;
  247.        
  248.         cout <<"Enter the lvl"<<endl;
  249.         int level;
  250.         cin>> level;
  251.         PrintTreeLvl(Tree,level);
  252.         cout<<"Enter node"<<endl;
  253.         double x;
  254.         cin>>x;
  255.     //  cout<< Search(Tree,x);
  256.     //  cout << endl;
  257.         SearchWay(Tree, x);
  258.         DelTree(Tree);
  259.         system("PAUSE");
  260.     return 0;
  261. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement