fork download
  1. #include<stdio.h>
  2.  
  3. #include<stdlib.h>
  4.  
  5. struct node{
  6.  
  7. int data;
  8.  
  9. struct node *right,*left;
  10.  
  11. }*root=NULL;
  12.  
  13. int max=0;
  14.  
  15. struct node *newnode(int k){
  16.  
  17. struct node *temp=(struct node *)malloc(sizeof(struct node));
  18.  
  19. temp->data=k;
  20.  
  21. temp->right=temp->left=NULL;
  22.  
  23. return temp;
  24.  
  25. }
  26.  
  27. void height(struct node *root,int d){
  28.  
  29. if(root==NULL){
  30.  
  31. return;
  32.  
  33. }
  34.  
  35. printf("Node:%d,Height: %d\n",root->data,d);
  36.  
  37. if(d>max){
  38.  
  39. max=d;
  40.  
  41. }
  42.  
  43. height(root->left,++d);
  44.  
  45. //here actually ++d and then --d thats why i have used d in next step
  46.  
  47. // --d to go up ++d to go right
  48.  
  49. height(root->right,d);
  50.  
  51. --d;
  52.  
  53.  
  54.  
  55.  
  56.  
  57.  
  58.  
  59. }
  60.  
  61. int main(){
  62.  
  63. root = newnode(1);
  64.  
  65. root->left = newnode(5);
  66.  
  67. root->right = newnode(8);
  68.  
  69. root->left->left = newnode(2);
  70.  
  71. root->left->right = newnode(4);
  72.  
  73. root->right->left = newnode(9);
  74.  
  75. root->right->right = newnode(10);
  76.  
  77. root->right->right->right= newnode(13);
  78.  
  79.  
  80.  
  81. height(root,0);
  82.  
  83. printf("\nHeight: %d",max);
  84.  
  85. return 0;
  86.  
  87.  
  88. }
Success #stdin #stdout 0s 2244KB
stdin
Standard input is empty
stdout
Node:1,Height: 0
Node:5,Height: 1
Node:2,Height: 2
Node:4,Height: 2
Node:8,Height: 1
Node:9,Height: 2
Node:10,Height: 2
Node:13,Height: 3

Height: 3