Advertisement
Guest User

Untitled

a guest
Oct 9th, 2015
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.35 KB | None | 0 0
  1. public void bringToRoot(Key k) {
  2.         root = bringToRoot(k, root);
  3.         printTree(root);
  4.     }
  5.     public Node bringToRoot(Key k, Node x) {
  6.        
  7.         if(x == null) { return x; }
  8.         if(isChildOfCurrent(k, x)) {
  9.             if(k.compareTo(x.right.key) == 0) { return rotateLeft(x); }
  10.             else if(k.compareTo(x.left.key) == 0){ return rotateRight(x);}
  11.         }
  12.         else{
  13.             if(k.compareTo(x.key) < 0) { return bringToRoot(k, x.left); }
  14.             else                       { return bringToRoot(k, x.right); }
  15.         }
  16.         StdOut.println(x.N);
  17.         return x;
  18.     }
  19.     private Boolean isChildOfCurrent(Key k, Node x) {
  20.         if(k.compareTo(x.left.key) == 0) { return true; }
  21.         if(k.compareTo(x.right.key) == 0) { return true; }
  22.         return false;
  23.     }
  24.    
  25.     public void printTree(Node x) {
  26.         if( x == null) return;
  27.         printTree(x.left);
  28.         StdOut.print(" " + x.key + " ");
  29.         printTree(x.right);
  30.     }
  31.    
  32.     private Node rotateLeft(Node h) {
  33.         //if(h.right == null) { return h; }
  34.         Node x = h.right;
  35.         h.right = x.left;
  36.         x.left = h;
  37.         x.N = h.N;
  38.         h.N = size(h.left) + size(h.right) + 1;
  39.         return x;
  40.     }
  41.     private Node rotateRight(Node h) {
  42.         //if(h.left == null ) { return h; }
  43.         Node x = h.left;
  44.         h.left = x.right;
  45.         x.right = h;
  46.         x.N = h.N;
  47.         h.N = size(h.left) + size(h.right) + 1;
  48.         return x;
  49.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement