Advertisement
vkichukova

Untitled

Jan 21st, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. #include<iostream>
  2. #include<queue>
  3. using namespace std;
  4.  
  5. template<class T>
  6. struct Node
  7. {
  8. T data;
  9. Node<T> *left, *right;
  10.  
  11. Node(int data)
  12. {
  13. this->data = data;
  14. left = NULL;
  15. right = NULL;
  16. }
  17. };
  18.  
  19. template<class T>
  20. class Tree
  21. {
  22. Node<T>* root;
  23. queue<Node<T>*> q;
  24.  
  25. public:
  26. Tree()
  27. {
  28. root = NULL;
  29. }
  30.  
  31. void addNode(Node<T> *newNode)
  32. {
  33. if(!root)
  34. {
  35. root = newNode;
  36. q.push(root);
  37. return;
  38. }
  39.  
  40. Node<T> *n = q.front();
  41. if(n->left && n->right)
  42. {
  43. q.pop();
  44. n = q.front();
  45. }
  46. if(!n->left)
  47. n->left = newNode;
  48. else if(!n->right)
  49. n->right = newNode;
  50.  
  51. q.push(newNode);
  52. }
  53. void createTree()
  54. {
  55. char c;
  56. do
  57. {
  58. int x;
  59. cout << "Element: "; cin >> x;
  60. addNode(new Node<T>(x));
  61.  
  62. cout << "New element y/n? "; cin >> c;
  63. } while (c == 'y');
  64. }
  65. void delTree(Node<T> *_root)
  66. {
  67. if (_root)
  68. {
  69. delTree(_root->left);
  70. delTree(_root->right);
  71. delete _root;
  72. _root = nullptr;
  73. }
  74. }
  75. void printHelpBFS(Node<T>* _root)
  76. {
  77. if(_root)
  78. {
  79. queue<Node<T>*> q;
  80. q.push(_root);
  81. while(!q.empty())
  82. {
  83. Node<T> *helper = q.front();
  84. q.pop();
  85. cout << helper->data << " ";
  86. if(helper->left)
  87. q.push(helper->left);
  88. if(helper->right)
  89. q.push(helper->right);
  90. }
  91. }
  92. }
  93. void printBFS()
  94. {
  95. printHelpBFS(this->root);
  96. }
  97. void printHelpDFS(Node<T>* _root)
  98. {
  99. if(_root)
  100. {
  101. printHelpDFS(_root->left);
  102. cout << _root->data << " ";
  103. printHelpDFS(_root->right);
  104. }
  105. }
  106. void printDFS()
  107. {
  108. printHelpDFS(this->root);
  109. }
  110. };
  111.  
  112. int main()
  113. {
  114. Tree<int> t;
  115. t.createTree();
  116.  
  117. t.printDFS();
  118. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement