fork download
  1. // title:Height of BST
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4. struct BSTNode
  5. {
  6. int data;
  7. struct BSTNode *left,*right;
  8. BSTNode(int val)
  9. {
  10. this->data=val;
  11. this->left=this->right=NULL;
  12. }
  13. };
  14. struct BSTNode * insert(struct BSTNode *root,int n)
  15. {
  16. if(root==NULL)
  17. return new BSTNode(n);
  18. else if(n<root->data)
  19. root->left=insert(root->left,n);
  20. else if(n>=root->data)
  21. root->right=insert(root->right,n);
  22. return root;
  23. }
  24. int height(struct BSTNode * root)
  25. {
  26. if(root==NULL)
  27. return 0;
  28. int lh=height(root->left);
  29. int rh=height(root->right);
  30. return max(lh,rh)+1;
  31. }
  32. int main(){
  33. // write your code here
  34. int tq;
  35. cin>>tq;
  36. while(tq--)
  37. {
  38. int n;
  39. cin>>n;
  40. struct BSTNode * root=NULL;
  41. for(int i=0;i<n;i++)
  42. {
  43. int x;
  44. cin>>x;
  45. root=insert(root,x);
  46. }
  47. int h=0;
  48. cout<<height(root)-1;
  49. cout<<"\n";
  50. }
  51. return 0;
  52. }
Success #stdin #stdout 0.01s 5476KB
stdin
1
5
1 5 6 8 10
stdout
4