Advertisement
Guest User

Untitled

a guest
Nov 12th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. #include "pch.h"
  2. #include <iostream>
  3. using namespace std;
  4.  
  5.  
  6. struct Ttree
  7. {
  8. int val;
  9. Ttree *left, *right;
  10. };
  11.  
  12. struct Ttree *addNode(int x, Ttree *tree)
  13. {
  14. if (tree == NULL)
  15. {
  16. tree = new Ttree;
  17. tree->val = x;
  18. tree->left = NULL;
  19. tree->right = NULL;
  20. }
  21. else
  22. {
  23. if (x < tree->val)
  24. tree->left = addNode(x, tree->left);
  25. else
  26. tree->right = addNode(x, tree->right);
  27. }
  28. return tree;
  29. }
  30.  
  31.  
  32. void printLeafs(Ttree *root)
  33. {
  34. if (root)
  35. {
  36. printLeafs(root->left);
  37. if (!root->left && !root->right)
  38. cout << root->val << endl;
  39. printLeafs(root->right);
  40. }
  41. }
  42.  
  43.  
  44. void print_Tree(Ttree *p, int level)
  45. {
  46. if (p)
  47. {
  48. print_Tree(p->right, level + 1);
  49. for (int i = 0; i < level; i++) cout << " ";
  50. cout << p->val ;
  51. cout << endl;
  52.  
  53. print_Tree(p->left, level + 1);
  54. }
  55. }
  56.  
  57. int dep_count=0;
  58.  
  59. int max(int x, int y)
  60. {
  61. if (x > y)
  62. {
  63. return x;
  64. }
  65. }
  66.  
  67. int Depth(Ttree *Ptr, int dep_count)
  68. {
  69. if (Ptr == NULL)
  70. return dep_count;
  71.  
  72. return max(Depth(Ptr->left, dep_count + 1), Depth(Ptr->right, dep_count + 1));
  73. }
  74.  
  75. int main()
  76. {
  77. int num = 0;
  78. cin >> num;
  79. Ttree *root = NULL;
  80. while (num != 0)
  81. {
  82. root=addNode(num,root);
  83. cin >> num;
  84. }
  85. printLeafs(root);
  86.  
  87. print_Tree(root, Depth(root, dep_count));
  88. system("pause");
  89. return 0;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement