fork download
  1. //
  2. // main.cpp
  3. // Height of Binary Tree
  4. //
  5. // Created by Himanshu on 11/09/21.
  6. //
  7.  
  8. #include <iostream>
  9. #include <queue>
  10. using namespace std;
  11.  
  12. struct node {
  13. int info = 0;
  14. struct node *left, *right;
  15. };
  16. typedef struct node Node;
  17.  
  18. node* newNode(int data)
  19. {
  20. node* Node = new node();
  21. Node->info = data;
  22. Node->left = NULL;
  23. Node->right = NULL;
  24.  
  25. return(Node);
  26. }
  27.  
  28.  
  29. int maxHeight (Node *root) {
  30. if (!root) {
  31. return -1;
  32. }
  33. int leftHt = maxHeight(root->left);
  34. int rightHt = maxHeight(root->right);
  35.  
  36. if (leftHt > rightHt) {
  37. return (leftHt + 1);
  38. } else {
  39. return (rightHt + 1);
  40. }
  41. }
  42.  
  43.  
  44. int main() {
  45. Node *root = newNode(1);
  46. root->left = newNode(20);
  47. root->right = newNode(21);
  48. root->right->left = newNode(30);
  49. root->right->right = newNode(31);
  50.  
  51. cout<<"The height of given tree is: "<<maxHeight(root)<<endl;
  52.  
  53. return 0;
  54. }
  55.  
  56.  
Success #stdin #stdout 0.01s 5512KB
stdin
Standard input is empty
stdout
The height of given tree is: 2