Advertisement
Guest User

avl tree

a guest
Mar 24th, 2017
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | None | 0 0
  1. //solution = chainLength is 3
  2. std::string backtrack(Node * x, std::string state){
  3.   if(x->left){
  4.     backtrack(x->left, state + 'L');
  5.   }
  6.  
  7.   if(state.length() == 3){
  8.     return state.substr(0, 2);
  9.   }
  10.  
  11.   if(x->right){
  12.     backtrack(x->right, state + 'R');
  13.   }
  14. }
  15.  
  16.   //
  17.   // Check if node x is unbalanced (i.e., the heights of its
  18.   // two children differ by more than one).  If it is, rebalance
  19.   // at x using one of rotateLeft, rotateRight, doubleRotateLeft,
  20.   // or doubleRotateRight, whichever is appropriate.
  21.   //
  22. void balance( Node *& x ) {
  23.   int balance = -1;
  24.  
  25.   if(x){
  26.     int leftHeight = ( x->left ? x->left->height : -1 );
  27.     int rightHeight = ( x->right ? x->right->height : -1 );
  28.     balance = leftHeight - rightHeight;
  29.   }
  30.  
  31.   bool isBalanced = abs(balance) <= 1;
  32.  
  33.   if(isBalanced){
  34.     return;
  35.   }
  36.  
  37.   std::string myCase = backtrack(x, "");
  38.  
  39.   if(myCase == "LL"){
  40.     rotateRight(x);
  41.   }
  42.   if(myCase == "LR"){
  43.     doubleRotateRight(x);
  44.   }
  45.   if(myCase == "RL"){
  46.     doubleRotateLeft(x);
  47.   }
  48.   if(myCase == "RR"){
  49.     rotateLeft(x);
  50.   }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement