Advertisement
Guest User

Untitled

a guest
Nov 27th, 2015
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 7.83 KB | None | 0 0
  1. #include "stdafx.h"
  2.  
  3. #include <iostream>
  4. #include <fstream>
  5.  
  6. #pragma comment(lib,"openbgi_vc90x.lib")
  7. using namespace std;
  8. const int LEN_STACK = 25;
  9. bool FLAG = 1;
  10.  
  11. typedef char Elem;
  12. struct node {//струтура элементов дерева
  13.     Elem name;
  14.     node *left;
  15.     node *right;
  16.     // constructor
  17.     node() { left = NULL; right = NULL; }
  18. };
  19. struct les{
  20.     Elem name;
  21.     les* root_of_first_tree;
  22.     les* next;
  23.     les() { root_of_first_tree = NULL; next = NULL; }
  24. };
  25.  
  26.  
  27. typedef node *binTree;
  28. typedef les *forest;
  29. //Elem GetSimbol(std::istream & in);//получает символ из входного потока
  30. //void ReadTree(binTree & y, std::istream & in);//обрабатывает символы скобочной записи
  31. //void  MakeTree(binTree & y, std::istream & in);//создает элементы дерева
  32. void Destroy(binTree &b);//удаляет дерево
  33. inline bool IsEmpty(const binTree &b);//проверка на пустоту
  34. inline bool IsEmptyF(const forest &f);
  35. Elem Name(binTree b); //получает значение элемента дерева
  36. void Les(binTree b, forest f);
  37. void PaintLes(forest f, int level);
  38.  
  39. bool PaintLeafBT(int x1, int x2, int y, binTree leaf, int level, char f);//рисует элементы дерева
  40. void PaintBT(binTree root);//рисует бинарное дерево
  41. void BinTree(binTree root);
  42. void PaintTree(binTree b, int level);
  43. void PaintLes(binTree b, int level);
  44.  
  45. void BFS(binTree root);//делает обход в ширину дерева
  46. void InFIFO(binTree* fifo, int & last, binTree y);//заносит элементы дерева  в очередь
  47.  
  48.  
  49. int main()
  50. {
  51.     int i = 0;
  52.     ifstream fin;
  53.     binTree Root;
  54.     forest LES = new les;
  55.     char ch = 0;
  56.     char name[50] = { 0 };
  57.  
  58.  
  59.     cout << "1. Enter a list of console\n"
  60.         << "2. enter a list of file\n"
  61.         << "Number: ";
  62. cin >> i;
  63.     //cin.sync();
  64.     switch (i)
  65.     {
  66.     case 1:
  67.         cout << "Enter list:" << std::endl;
  68.         cin >> ch;
  69.         ReadTree(Root, cin);
  70.         break;
  71.     case 2:
  72.        
  73.         fin.open("BT.txt");
  74.         if (!fin.is_open())
  75.         {
  76.             cout << "Error: can't open file " << '\n';
  77.             return 1;
  78.         }
  79.  
  80.         ReadTree(Root, fin);
  81.         BinTree(Root);
  82.         cout << "\nForest:\n";
  83.         Les(Root, LES);
  84.         PaintLes(LES, 50);
  85.         fin.close();
  86.         cout << "...............................\n";
  87.         break;
  88.     default:
  89.         cout << "Error: wrong number!\n";
  90.         return 1;
  91.     }
  92.  
  93.     //BinTree(Root);
  94.     //cout << "\nForest:\n";
  95.     //Les(Root, LES);
  96.     //PaintLes(LES, 50);
  97.     //PaintBT(Root);
  98.    
  99.    
  100.     BFS(Root);
  101.     Destroy(Root);
  102.     system("pause");
  103.     return 0;
  104. }
  105. Elem RootBT(node* b){
  106.     if (b == NULL) { cerr << "Error: RootBT(null) \n"; return 0; }
  107.     else return b->name;
  108.  
  109. }
  110. node* Left(node* b){
  111.     if (b == NULL) { cerr << "Error: Left(null) \n"; return NULL; }
  112.     else return b->left;
  113. }
  114. node* Right(node* b){
  115.     if (b == NULL) { cerr << "Error: Right(null) \n"; return NULL; }
  116.     else return b->right;
  117. }
  118.  
  119. //блок создания дерева  и работы с ним
  120. /*
  121. Elem GetSimbol(istream & in)
  122. {
  123.     if (!FLAG) //если при считывании произошла ошибка или строка закончилась
  124.     {
  125.         return EOF;
  126.     }
  127.  
  128.     Elem x = ' ';
  129.     x = in.get();
  130.     while (x == ' ' && in.good() && x != '\n')//до тех пор пока следующий символ не будет символом скобочной записи
  131.     {
  132.         x = in.get();
  133.     }
  134.  
  135.     if (x != '\n' && in.good())
  136.     {
  137.         return x;
  138.     }
  139.     else
  140.     {
  141.         FLAG = false;
  142.         return EOF;
  143.     }
  144.     return x;
  145. }
  146.  
  147. void ReadTree(binTree & y, istream & in)
  148. {
  149.     Elem x = GetSimbol(in);
  150.  
  151.     if (x == '(')//если новая ветвь, то создаем узел
  152.     {
  153.         MakeTree(y, in);
  154.         return;
  155.     }
  156.     else if (x != EOF && x != ')') //если нет, то выдаем ошибку
  157.     {
  158.         cout << "Error: incorrect symbol in expession\n";
  159.         exit(1);
  160.     }
  161.     y = NULL;
  162. }
  163.  
  164. void  MakeTree(binTree & y, istream & in)
  165. {
  166.     Elem x = GetSimbol(in);
  167.  
  168.     if (x == EOF)
  169.     {
  170.         cout << "Error: in fail\n";
  171.         exit(1);
  172.     }
  173.  
  174.     y = new node;
  175.     if (y == NULL)
  176.     {
  177.         cout << "Error: memory\n";
  178.         exit(1);
  179.     }
  180.  
  181.     y->name = x;//заполняем дерево
  182.     ReadTree(y->left, in);
  183.     ReadTree(y->right, in);
  184. }*/
  185.  
  186. void Destroy(binTree &b)
  187. {
  188.     if (!IsEmpty(b))    {
  189.         Destroy(b->left);
  190.         Destroy(b->right);
  191.         delete b;
  192.         b = NULL;
  193.     }
  194. }
  195.  
  196. bool IsEmpty(const binTree &b)
  197. {
  198.     return b == NULL;
  199. }
  200. bool IsEmptyF(const forest &f)
  201. {
  202.     if (f != NULL)
  203.         return !f->name;
  204.     return f == NULL;
  205. }
  206. Elem Name(binTree b)            // для непустого бин.дерева
  207. {
  208.     if (IsEmpty(b))
  209.     {
  210.         cerr << "Error: Name(null) \n";
  211.         exit(1);
  212.     }
  213.     else
  214.     {
  215.         return b->name;
  216.     }
  217. }
  218.  
  219. /*
  220. void BinTree(binTree root)
  221. {
  222.     cout << "\nBinTree:\n";
  223.     if (IsEmpty(root))
  224.     {
  225.         cout << "\nBinTree is Empty\n";
  226.     }
  227.     else
  228.     {
  229.         PaintTree(root, 50);
  230.     }
  231.     cout << "...............................\n";
  232. }*/
  233. node* consoleEnter(){
  234.     cout << "Введите бинарное дерево:\n";
  235.     cin.clear();
  236.     cin.sync();
  237.     cin >> arr;
  238.  
  239.     ofstream fout("Data.txt");
  240.     fout << arr;
  241.     fout.close();
  242.  
  243.     ifstream fin("Data.txt");
  244.     node* b = enterBT(fin);
  245.     fin.close();
  246.     return b;
  247.  
  248.  
  249. }
  250.  
  251. node* enterBT(ifstream &infile)
  252. {
  253.     char ch;
  254.     node* p, *q;
  255.     if (!(infile >> ch)){
  256.         if (flag) cout << "Файл пуст\n";
  257.         return NULL;
  258.     }
  259.     while ((ch == '(') || (ch == ')')){
  260.         if (!(infile >> ch)){
  261.             if (flag) cout << "Ошибка входных данных\n";
  262.             return NULL;
  263.         }
  264.     }
  265.     if (ch == '^') return NULL;
  266.     else {
  267.         flag = false;
  268.         p = enterBT(infile);
  269.         q = enterBT(infile);
  270.         return ConsBT(ch, p, q);
  271.     }
  272. }
  273. //вывод дерева
  274. void PaintTree(node* b, int n)
  275. {
  276.     tab(n);
  277.     if (!IsEmpty(b))
  278.     {
  279.  
  280.         cout << RootBT(b) << endl;
  281.         //output << RootBT(b) << endl;
  282.         if (!IsEmpty(b->left) || !IsEmpty(b->right)){
  283.             PaintTree(Left(b), n + 1);
  284.             PaintTree(Right(b), n + 1);
  285.         }
  286.     }
  287.     else {
  288.         cout << "^\n";
  289.         //output << "^\n";
  290.     }
  291. }
  292.  
  293.  
  294. /*
  295. void PaintTree(binTree b, int level)
  296. {
  297.     int i = 0;
  298.     if (IsEmpty(b))
  299.     {
  300.         return;
  301.     }
  302.  
  303.     for (i = 0; i<level; i++)
  304.     {
  305.         cout << '|';
  306.     }
  307.     cout << Name(b) << '\n';
  308.     PaintTree(b->left, level-5);
  309.     PaintTree(b->right, level);
  310. }*/
  311. void PaintLes(forest f, int level)
  312. {
  313.     int i = 0;
  314.     if (IsEmptyF(f))
  315.     {
  316.         return;
  317.     }
  318.     for (i = 0; i<level; i++)
  319.     {
  320.         cout << '|';
  321.     }
  322.     cout << f->name << '\n';
  323.     PaintLes(f->root_of_first_tree, level - 5);
  324.     PaintLes(f->next, level);
  325. }
  326. ///////////// ??????
  327.  
  328. void Les(binTree b, forest f)
  329. {
  330.     //forest save = new les;
  331.     //f = new les;
  332.     if (IsEmpty(b))
  333.     {
  334.         //delete(f);
  335.         f->name = NULL;
  336.         return;
  337.     }  
  338.     else
  339.     {
  340.         f->name=b->name;
  341.         f->next = new les;
  342.         Les(b->right, f->next);
  343.         f->root_of_first_tree = new les;
  344.         Les(b->left, f->root_of_first_tree);
  345.     }
  346.    
  347. }
  348.  
  349. //блок обхода в ширину
  350.  
  351. void BFS(binTree root)
  352. {
  353.     cout << "\nBreadth-first search\n\n";
  354.     binTree tmp = root;
  355.     if (IsEmpty(root))
  356.     {
  357.         cout << "Forest is empty\n\n...............................\n";
  358.         return;
  359.     }
  360.     int first = 0; //инициализируем очередь
  361.     int last = 0;
  362.     binTree fifo[LEN_STACK] = { 0 };
  363.  
  364.     InFIFO(fifo, last, tmp); //заполняем её вершинами деревьев
  365.     while (first != last) //движемся по массивую, добавляя вершины поддеревьев
  366.     {
  367.         tmp = fifo[first];
  368.         InFIFO(fifo, last, tmp->left);
  369.         first++;
  370.     }
  371.  
  372. cout << "Elemet of forest:\n";
  373.     first = 0;
  374.  
  375.  
  376.     while (fifo[first] != NULL) //выводим массив
  377.     {
  378.         cout << Name(fifo[first]) << ' ';
  379.         first++;
  380.     }
  381.     cout << "\n...............................\n";
  382. }
  383.  
  384. void InFIFO(binTree* fifo, int & last, binTree y)
  385. {
  386.     while (!IsEmpty(y) && last != LEN_STACK) //заносим в очередь все левые узлы
  387.     {
  388.         fifo[last] = y;
  389.         last++;
  390.         y = y->right;
  391.     }
  392.  
  393.     if (last == LEN_STACK)
  394.     {
  395.         last = 0;
  396.         cout << "Error: last=LEN\n";
  397.     }
  398. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement