Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public void bringToRoot(Key k) {
- root = bringToRoot(k, root);
- printTree(root);
- }
- public Node bringToRoot(Key k, Node x) {
- if(x == null) { return x; }
- if(isChildOfCurrent(k, x)) {
- if(k.compareTo(x.right.key) == 0) { return rotateLeft(x); }
- else if(k.compareTo(x.left.key) == 0){ return rotateRight(x);}
- }
- else{
- if(k.compareTo(x.key) < 0) { return bringToRoot(k, x.left); }
- else { return bringToRoot(k, x.right); }
- }
- StdOut.println(x.N);
- return x;
- }
- private Boolean isChildOfCurrent(Key k, Node x) {
- if(k.compareTo(x.left.key) == 0) { return true; }
- if(k.compareTo(x.right.key) == 0) { return true; }
- return false;
- }
- public void printTree(Node x) {
- if( x == null) return;
- printTree(x.left);
- StdOut.print(" " + x.key + " ");
- printTree(x.right);
- }
- private Node rotateLeft(Node h) {
- //if(h.right == null) { return h; }
- Node x = h.right;
- h.right = x.left;
- x.left = h;
- x.N = h.N;
- h.N = size(h.left) + size(h.right) + 1;
- return x;
- }
- private Node rotateRight(Node h) {
- //if(h.left == null ) { return h; }
- Node x = h.left;
- h.left = x.right;
- x.right = h;
- x.N = h.N;
- h.N = size(h.left) + size(h.right) + 1;
- return x;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement