fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. struct treenode
  4. {
  5. int data;
  6. treenode* right;
  7. treenode* left;
  8. };
  9. treenode* createnode (int data)
  10. {
  11. treenode* temp = (treenode*)malloc(sizeof(treenode));
  12. temp->data = data;
  13. temp->left = NULL;
  14. temp->right = NULL;
  15. return temp;
  16. }
  17. treenode* insertion (treenode* root, int data)
  18. {
  19. if(root == NULL)
  20. {
  21. root = createnode(data);
  22. return root; // << it simply return the references of the root to if/else block according to the condition;
  23. }
  24. else
  25. {
  26. if(root->data > data)
  27. {
  28. root->left = insertion(root->left, data);
  29. }
  30. else
  31. {
  32. root->right = insertion(root->right, data);
  33. }
  34. return root; // << returns the initial root value to the main function so that the other comparisons can occur with root.
  35. }
  36. }
  37. int heightcount (treenode* root)
  38. {
  39. if(root == NULL)
  40. {
  41. return NULL;
  42. }
  43. else
  44. {
  45. if(root->left == NULL && root->right == NULL)
  46. {
  47. return 0;
  48. }
  49. else
  50. {
  51. int counta = heightcount(root->right) + 1;
  52. int countb = heightcount(root->left) + 1;
  53. if(counta > countb)
  54. return counta;
  55. else
  56. return countb;
  57.  
  58. }
  59. }
  60. }
  61. int main()
  62. {
  63. treenode* root = NULL;
  64. root = insertion (root, 10);
  65. root = insertion (root, 15);
  66. root = insertion (root, 5);
  67. root = insertion (root, 1);
  68. root = insertion (root, 6);
  69. root = insertion (root, 11);
  70. root = insertion (root, 16);
  71. root = insertion (root, 20);
  72. //root = insertion (root, 200);
  73.  
  74. printf("Height of the tree: %d", heightcount (root)-1);
  75. printf("\nLevel: %d", heightcount (root));
  76.  
  77. }
  78.  
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Height of the tree: 2
Level: 3