Advertisement
193030

Kontrolno 1.zadacha

Dec 8th, 2020
115
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5. //string input = "amd*fu***e**ckl**r***";
  6.  
  7.  
  8. // The input is from the console
  9.  
  10. struct Node
  11. {
  12. struct Node* lchild;
  13. char data;
  14. struct Node* rchild;
  15. };
  16.  
  17. typedef Node* point;
  18. point Root;
  19. void Create_B_Tree(point& P) {
  20. char x;
  21. cin >> x;
  22. if (x == '*') P = NULL;
  23. else {
  24. P = new Node;
  25. P->data = x;
  26. // cout << "left of " << P->data << "=";
  27. Create_B_Tree(P->lchild);
  28. // cout << "right of" << P->data << "=";
  29. Create_B_Tree(P->rchild);
  30. }
  31. }
  32.  
  33.  
  34.  
  35. int height(struct Node* p)
  36. {
  37. if (p)
  38. {
  39. return 1 + max(height(p->rchild), height(p->lchild));
  40. }
  41. return 0;
  42. }
  43.  
  44. /* Print nodes at a given level */
  45. void printGivenLevel(struct Node* p, int level)
  46. {
  47. if (p == NULL)
  48. return;
  49. if (level == 1)
  50. {
  51. printf("%c ", p->data);
  52. if (p->lchild)
  53. cout << " left child of" << p->data << " is: " << p->lchild->data << endl;
  54. else
  55. cout << p->data << " doesnt have left child" << endl;
  56.  
  57. if (p->rchild)
  58. cout << " right child of" << p->data << " is: " << p ->rchild->data << endl;
  59. else
  60. cout << p->data << " doesnt have right child" << endl;
  61.  
  62. }
  63. else if (level > 1)
  64. {
  65. printGivenLevel(p->lchild, level - 1);
  66. printGivenLevel(p->rchild, level - 1);
  67. }
  68. }
  69.  
  70. void printLevelOrder(struct Node* p)
  71. {
  72. int h = height(p);
  73. int i;
  74. for (i = 1; i <= h; i++)
  75. {
  76. printGivenLevel(p, i);
  77. printf("\n");
  78. }
  79. }
  80.  
  81.  
  82. int main()
  83. {
  84. cout << "Enter the whole input" << endl;
  85. Root = NULL;
  86. Create_B_Tree(Root);
  87. cout << endl;
  88. printLevelOrder(Root);
  89. }
Advertisement
RAW Paste Data Copied
Advertisement