Advertisement
Zander-Bandoly

Print Binary Tree

Mar 26th, 2019
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. #include <iostream>
  2. #include "bintree.h"
  3. #include <cstdlib>
  4. #include <queue>
  5.  
  6. using namespace std;
  7. using namespace main_savitch_10;
  8.  
  9. template <typename T>
  10. void display_complete_tree (const binary_tree_node<T>* t) {
  11.  
  12. if (t == NULL)
  13. return;
  14.  
  15. queue<const binary_tree_node<T>* > q;
  16.  
  17. q.push(t);
  18.  
  19. while (q.empty() == false) {
  20.  
  21. int size = q.size();
  22.  
  23. while (size > 0) {
  24.  
  25. const binary_tree_node<string> *node = q.front();
  26.  
  27. cout << node->data() << " ";
  28.  
  29. q.pop();
  30.  
  31. if (node->left() != NULL) {
  32.  
  33. q.push(node->left());
  34.  
  35. } else if (node->left() == NULL && node->right() != NULL){
  36.  
  37. cout << "NULL ";
  38.  
  39. }
  40.  
  41. if (node->right() != NULL) {
  42.  
  43. q.push(node->right());
  44.  
  45. } else if (node->right() == NULL && node->left() != NULL){
  46.  
  47. cout << "NULL ";
  48.  
  49. }
  50.  
  51. size--;
  52.  
  53. }
  54.  
  55. cout << endl;
  56.  
  57. }
  58.  
  59. }
  60.  
  61.  
  62. binary_tree_node<string>* create_int_tree()
  63. {
  64. binary_tree_node<string>* t1 = new binary_tree_node<string>("14");
  65. binary_tree_node<string>* t2 = new binary_tree_node<string>("32");
  66. binary_tree_node<string>* t3 = new binary_tree_node<string>("6");
  67. binary_tree_node<string>* t4 = new binary_tree_node<string>("23", NULL, t1);
  68. binary_tree_node<string>* t5 = new binary_tree_node<string>("9", t2, t3);
  69. binary_tree_node<string>* t6 = new binary_tree_node<string>("17", t4, t5);
  70. return t6;
  71. }
  72.  
  73. int main()
  74. {
  75. binary_tree_node<string>* t = create_int_tree();
  76. display_complete_tree(t);
  77. return EXIT_SUCCESS;
  78. }
  79.  
  80.  
  81. // returned: root of binary tree of integers
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement