Advertisement
Guest User

BTS

a guest
Nov 24th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.17 KB | None | 0 0
  1. //по входной последовательности построить дерево бинарного поиска и
  2. //9.найти длину пути из узла а в узел б; если такого пути не существует, то вывести сообщение об этом;
  3. #include <iostream>
  4. #include <fstream>
  5. using namespace std;
  6. ifstream in("input.txt");
  7. //ofstream out("output.txt");
  8. #define out cout
  9.  
  10. struct tree {
  11.     int inf;//информация узла
  12.     tree *left, *right;//указатели на левого и правого потомка
  13. };
  14.  
  15. tree *root;
  16.  
  17. void add (int x, tree *&root) { //функция добавления элемента в дерево бинарного поиска
  18.     if (!root) { //если узел пуст
  19.         root= new tree;
  20.         root->inf = x;
  21.         root->left = root->right = NULL;
  22.     } else if (x < root->inf) // если узел не пуст
  23.         add(x, root->left);
  24.     else add(x, root->right);
  25. }
  26.  
  27. void deleteTree (tree *&root) { //функция удаления дерева
  28.     if (root) {
  29.         deleteTree(root->left);
  30.         deleteTree(root->right);
  31.         delete(root);
  32.         root=NULL;
  33.     }
  34. }
  35.  
  36. void PrintList (tree *root, int lvl) { //функция для печати листьев
  37.         for (int i = 0; i < lvl; i++) cout << "|  ";
  38.     if (root) {
  39.         cout << root->inf << endl;
  40.         PrintList(root->right, lvl + 1);
  41.         PrintList(root->left, lvl + 1);
  42. //      cout << endl;
  43.         /*if ((root->left==NULL) && (root->right==NULL)) out<<root->inf<<" ";
  44.         else {
  45.             PrintList(root->left, i + 1);
  46.             PrintList(root->right, i + 1);
  47.         }*/
  48.     } else  cout << "*\n";
  49. }
  50.  
  51. int findPath(tree* root, tree* target) {
  52.     tree* node = root;
  53.     int path = 0;
  54.     while (node) {
  55.        
  56.         if (node->inf < target->inf)
  57.         path++;
  58.     }
  59. }
  60. /*
  61. 1
  62.     2
  63.         4
  64.         4
  65.     3
  66.         5
  67.         6
  68. */
  69.  
  70. void preorder (tree *root) { //прямой обход
  71.     if (root) {
  72.         out<<root->inf<<" ";
  73.         preorder(root->left);
  74.         preorder(root->right);
  75.     }
  76. }
  77.  
  78. int main() {
  79.     int x;
  80.     while(in.peek() != EOF) {
  81.         in >> x;
  82.         add(x, root);
  83.         PrintList(root, 0);
  84.         cout << "=====================================\n";
  85.     }
  86.     //PrintList(root, 0);
  87.     deleteTree(root);
  88.     in.close();
  89.     return 0;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement