|
| 1 | +import java.util.Random; |
| 2 | + |
| 3 | +class Node { |
| 4 | + int key; |
| 5 | + int priority; |
| 6 | + Node left; |
| 7 | + Node right; |
| 8 | +} |
| 9 | + |
| 10 | +public class Treap { |
| 11 | + private Node createNode(int key) { |
| 12 | + Node newNode = new Node(); |
| 13 | + newNode.key = key; |
| 14 | + newNode.priority = new Random().nextInt(); |
| 15 | + newNode.left = newNode.right = null; |
| 16 | + return newNode; |
| 17 | + } |
| 18 | + |
| 19 | + private Node rotateRight(Node y) { |
| 20 | + Node x = y.left; |
| 21 | + Node T2 = x.right; |
| 22 | + |
| 23 | + x.right = y; |
| 24 | + y.left = T2; |
| 25 | + |
| 26 | + return x; |
| 27 | + } |
| 28 | + |
| 29 | + private Node rotateLeft(Node x) { |
| 30 | + Node y = x.right; |
| 31 | + Node T2 = y.left; |
| 32 | + |
| 33 | + y.left = x; |
| 34 | + x.right = T2; |
| 35 | + |
| 36 | + return y; |
| 37 | + } |
| 38 | + |
| 39 | + private Node insert(Node root, int key) { |
| 40 | + if (root == null) return createNode(key); |
| 41 | + |
| 42 | + if (key <= root.key) { |
| 43 | + root.left = insert(root.left, key); |
| 44 | + if (root.left.priority > root.priority) |
| 45 | + root = rotateRight(root); |
| 46 | + } else { |
| 47 | + root.right = insert(root.right, key); |
| 48 | + if (root.right.priority > root.priority) |
| 49 | + root = rotateLeft(root); |
| 50 | + } |
| 51 | + |
| 52 | + return root; |
| 53 | + } |
| 54 | + |
| 55 | + private void inorderTraversal(Node root) { |
| 56 | + if (root != null) { |
| 57 | + inorderTraversal(root.left); |
| 58 | + System.out.print("(" + root.key + ", " + root.priority + ") "); |
| 59 | + inorderTraversal(root.right); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + public static void main(String[] args) { |
| 64 | + Node root = null; |
| 65 | + |
| 66 | + Treap treap = new Treap(); |
| 67 | + root = treap.insert(root, 50); |
| 68 | + root = treap.insert(root, 30); |
| 69 | + root = treap.insert(root, 20); |
| 70 | + root = treap.insert(root, 40); |
| 71 | + root = treap.insert(root, 70); |
| 72 | + root = treap.insert(root, 60); |
| 73 | + root = treap.insert(root, 80); |
| 74 | + |
| 75 | + System.out.println("Inorder traversal of the treap:"); |
| 76 | + treap.inorderTraversal(root); |
| 77 | + System.out.println(); |
| 78 | + } |
| 79 | +} |
0 commit comments