Advertisement
Guest User

ALL

a guest
May 29th, 2015
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct Node{int key;Node* left;Node*right;
  5. Node(int k):key(k),left(NULL),right(NULL){}
  6. };
  7.  
  8. class BinTree{
  9. Node* root_;
  10. public:
  11. BinTree(){root_=NULL;}
  12. Node* getRoot(){return root_;}
  13. void insert(int k){
  14. Node* node=new Node(k);
  15. Node* pre=NULL;
  16. Node* post=root_;
  17. while(post!=NULL)
  18. {
  19. pre=post;
  20. if(k<=post->key)
  21. post=post->left;
  22. else
  23. post=post->right;
  24. }
  25. if(pre==NULL)
  26. root_=node;
  27. else if(k<=pre->key)
  28. pre->left=node;
  29. else
  30. pre->right=node;
  31.  
  32. }
  33.  
  34. int height(Node* tree)
  35. {
  36. int hLeft;
  37. int hRight;
  38. if(tree==NULL)
  39. return 0;
  40. hLeft=height(tree->left);
  41. hRight=height(tree->right);
  42.  
  43. int max;
  44. if(hLeft>hRight)
  45. max=hLeft;
  46. else
  47. max=hRight;
  48. return 1 + max;
  49. }
  50.  
  51. };
  52.  
  53.  
  54. int main()
  55. {
  56. BinTree s1;
  57. int h;
  58. int N;
  59. int k;
  60. cin>> N;
  61. for(int i=0;i<N;i++)
  62. {
  63. cin>>k;
  64. s1.insert(k);
  65. }
  66.  
  67. h=s1.height(s1.getRoot());
  68. cout<<h<<endl;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement