Advertisement
Guest User

Untitled

a guest
Jun 25th, 2017
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.23 KB | None | 0 0
  1. // bst.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <iostream>
  6.  
  7. using namespace std;
  8.  
  9. struct wezel
  10. {
  11.     int klucz;
  12.     wezel* lewe;
  13.     wezel* prawe;
  14. };
  15.  
  16. void insert_BST(int x, wezel* &w)
  17. {
  18.     if (w == NULL)
  19.     {
  20.         w = new wezel; w->klucz = x;
  21.         w->lewe = NULL; w->prawe = NULL;
  22.     }
  23.     else if (x < w->klucz) insert_BST(x, w->lewe);
  24.     else insert_BST(x, w->prawe);
  25. }
  26.  
  27. void built_BST(int n, wezel* &w)
  28. {
  29.     w = NULL;
  30.  
  31.     for (int i = 1; i <= n; i++)
  32.     {
  33.         cout << "wypisz wartosci: " << endl;
  34.         int x; cin >> x;
  35.         insert_BST(x, w);
  36.     }
  37. }
  38.  
  39. int wysokosc_drzewa(wezel *w)
  40. {
  41.     int h;
  42.     if (w != NULL)
  43.     {
  44.         int x = wysokosc_drzewa(w->lewe);
  45.         int y = wysokosc_drzewa(w->prawe);
  46.         if (x > y) h = x + 1;
  47.         else h = y + 1;
  48.     }
  49.     else h = 0;
  50.     return h;
  51. }
  52.  
  53. void wyswietl_drzewo_inorder(wezel *w, int h)
  54. {
  55.     if (w != NULL)
  56.     {
  57.         wyswietl_drzewo_inorder(w->lewe, h - 1);
  58.         for (int i = 1; i <= h; i++) cout << "    ";
  59.         cout << w->klucz << "\n";
  60.         wyswietl_drzewo_inorder(w->prawe, h - 1);
  61.     }
  62. }
  63.  
  64. void wyswietl_drzewo_preorder(wezel *w, int h)
  65. {
  66.     if (w != NULL)
  67.     {
  68.         wyswietl_drzewo_preorder(w->lewe, h - 1);
  69.         //for (int i = 1; i <= h; i++) cout << "    ";
  70.         cout << w->klucz << " ";
  71.         wyswietl_drzewo_preorder(w->prawe, h - 1);
  72.     }
  73. }
  74.  
  75. void wyswietl_drzewo_postorder(wezel *w, int h)
  76. {
  77.     if (w != NULL)
  78.     {
  79.         wyswietl_drzewo_postorder(w->lewe, h - 1);
  80.         wyswietl_drzewo_postorder(w->prawe, h - 1);
  81.         //for (int i = 1; i <= h; i++) cout << "    ";
  82.         cout << w->klucz << " ";
  83.          
  84.     }
  85. }
  86.  
  87. int main()
  88. {
  89.     wezel* drzewo = NULL;
  90.  
  91.     int n;
  92.     cout << "podaj n:"; cin >> n;
  93.     built_BST(n, drzewo);
  94.     int h = wysokosc_drzewa(drzewo);
  95.  
  96.     wyswietl_drzewo_inorder(drzewo, h);
  97.     cout << endl << endl;
  98.     wyswietl_drzewo_preorder(drzewo, h);
  99.     cout << endl << endl;
  100.     wyswietl_drzewo_postorder(drzewo, h);
  101.  
  102.     system("pause");
  103.     return 0;
  104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement