Advertisement
Guest User

Untitled

a guest
Nov 14th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. template<typename T>
  6. class Node {
  7. public:
  8. Node<T> *left, *right, *parent;
  9. T key;
  10.  
  11. Node(T key) {
  12. left = right = parent = NULL;
  13. this->key = key;
  14. }
  15.  
  16. };
  17.  
  18. template<typename T>
  19. class BST {
  20. public:
  21. Node<T> *root;
  22.  
  23. BST() {
  24. root = NULL;
  25. }
  26.  
  27. bool insert(const T& dane) {
  28.  
  29. Node<T> *x = root;
  30. Node<T> *y = root;
  31. if (root == NULL) {
  32. root = new Node<T>(dane);
  33. return true;
  34. }
  35. else {
  36. Node<T> * temp = new Node<T>(dane);
  37. while (x != NULL) {
  38. if (x->key == dane) {
  39.  
  40. return false;
  41. }
  42. else if (dane < x->key) {
  43. y = x;
  44. x = x->left;
  45. }
  46. else {
  47. y = x;
  48. x = x->right;
  49. }
  50. }
  51.  
  52. if (y->key < dane) {
  53. y->left = temp;
  54. temp->parent = y;
  55. }
  56. else {
  57. y->right = temp;
  58. temp->parent = y;
  59. }
  60. }
  61. return true;
  62. }
  63.  
  64. void PREORDER(Node<T> * dane)
  65. {
  66. cout << dane->key << endl;
  67. if (dane->left != NULL) PREORDER(dane->left);
  68. if (dane->right != NULL) PREORDER(dane->right);
  69. }
  70.  
  71. };
  72. int main(int argc, char** argv) {
  73.  
  74. BST<int> tmp;
  75.  
  76. tmp.insert(90);
  77. tmp.insert(85);
  78. tmp.insert(24);
  79. tmp.insert(5);
  80. tmp.insert(74);
  81.  
  82. tmp.PREORDER(tmp.root);
  83. /*tmp.insert(xd);
  84. xd = new Node(85);
  85. tmp.insert(xd);
  86. tmp.PREORDER(tmp.root);
  87. xd = new Node(24);
  88. tmp.insert(xd);
  89. xd = new Node(60);
  90. tmp.insert(xd);
  91. xd = new Node(75);
  92. tmp.insert(xd);
  93. xd = new Node(85);
  94. tmp.insert(xd);
  95. xd = new Node(85);
  96. tmp.insert(xd);
  97. xd = new Node(5);
  98. tmp.insert(xd);*/
  99.  
  100.  
  101.  
  102.  
  103. return 0;
  104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement