Advertisement
Guest User

albero

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