Advertisement
Guest User

Untitled

a guest
May 23rd, 2017
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct tree {
  6.  
  7. short int key;
  8.  
  9. tree *left;
  10.  
  11. tree *right;
  12.  
  13. };
  14.  
  15. tree *root = NULL;
  16.  
  17. int c = 0;
  18.  
  19. struct tree *ctree(tree *root, tree *r, int key) {
  20.  
  21. if (!r) {
  22.  
  23. r = new tree;
  24.  
  25. r->left = NULL;
  26.  
  27. r->right = NULL;
  28.  
  29. r->key = key;
  30.  
  31. if (!root) return r;
  32.  
  33. if (key % 2 == 0) root->right = r;
  34.  
  35. else root->left = r;
  36.  
  37. return r;
  38.  
  39. }
  40.  
  41. if (key % 2 == 0) ctree(r, root->right, key);
  42.  
  43. else ctree(r, root->left, key);
  44.  
  45. return root;
  46.  
  47. }
  48.  
  49. void preorder(tree *root) {
  50.  
  51. if (!root) return;
  52.  
  53. if (root->key) cout << root->key << " ";
  54.  
  55. preorder(root->left);
  56.  
  57. preorder(root->right);
  58.  
  59. c++;
  60.  
  61. }
  62.  
  63. void Destroy(tree *root) {
  64.  
  65. if (root) {
  66.  
  67. Destroy(root->left);
  68.  
  69. Destroy(root->right);
  70.  
  71. delete root;
  72.  
  73. }
  74.  
  75. root = 0;
  76.  
  77. }
  78.  
  79. int main() {
  80.  
  81. short int key;
  82.  
  83. cout << "Eneter '0' if u want to exite." << endl;
  84.  
  85. do {
  86.  
  87. cout << "key: ";
  88.  
  89. cin >> key;
  90.  
  91. root = ctree(root, root, key);
  92.  
  93. } while (key != 0);
  94.  
  95. preorder(root);
  96.  
  97. cout << endl << "The depth of tree is: " << (c -1) / 2<< endl;
  98.  
  99. Destroy(root);
  100.  
  101. system("pause");
  102.  
  103. return 0;
  104.  
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement