This is a slide Group Phil♂sophy
Binary Search Tree (BST)
A binary search tree 12 5 15 3 8 16 17 4 6 9 7
Binary Search Tree 2 • Construct binary search tree • Input[2, 4, 5, 1, 3] 1 4 3 5 • O(logN)
• What if the input is [1, 2, 3, 4, 5] ? 1 2 3 4 5 • A linked list. • Only O(N)
Some Self-Balancing Binary Search Trees • AVL(Adelson-Velskii & Landis Tree) • Red Black Tree • Size Balanced Tree • Treap
Treap a randomized binary search tree
A tree or a heap? 4 15 2 5 • Key [4, 2, 1, 3, 5] 11 19 • Priority [15, 11, 13, 18, 19] 1 3 18 13
Rotate right 4 2 rotate 2 5 1 4 left rotate 1 3 3 5
Rotate 4 2 30 10 2 5 1 4 50 10 30 20 right rotate 1 3 3 5 20 40 40 50
Insert Lets build a treap together!
Insert 2 Key = 4 10 Priority = 15 Left rotate 3 1 5 20 18 Right rotate 5 3 6 30 40 4 15
Search 2 10 Just as you do in the BST 1 4 18 15 3 5 20 30 6 40
Delete 2 10 Just do it! 1 6 Rotate then do it 15 12 4 7 15 13 8 3 5 40 19 30
2 10 Find node 6 1 6 Right rotate 15 12 6 Left rotate 6 Delete 6 4 7 15 13 8 3 5 40 19 30
Deeper understanding of treap
• DEF. mean that i is a proper ancestor of k. i k • If i is proper ancestor of k, i k 1 • Otherwise i k 0 Input array is [1, 2, 3, 4, 5] 2 Input priority is [0.3, 0.1, 0.8, 0.5, 0.9] 0.1 1 4 2 4 1 2 5 1 0.3 0.5 2 3 1 4 3 1 3 5 1 4 0 3 5 0 0.8 0.9
• The depth of node k: depth k i k E E E i k Pr i k i A i A i A
• DEF. X(i,k) denotes set of nodes which key value is between i and k. • For input array [2, 3, 1, 5, 4] • X(2,5)={2,3,4,5} • X(1,3)={1,2,3}
i • Lemma. For all , i has the smallest priority in X(i,k) k i k 1 iff
1 if i k k i 1 i k Pr i k 0 if i k k i 1 1 if i k i k 1 i k 1 k 1 1 n 1 E depth k Pr i k i k 1 k i 1 i k 1 i A i A i 1 i k 1 k n k 1 1 1 j j j 2 i 2 H 1 H 1 k n k 1 ln k ln n k 1 2 2 ln n 2
• depth(k) = O(logN) in expectation. • search(k) takes time O(depth(k)) = O(logN) in expectation. • insert(k) takes time O(depth(k))=O(logN) in expectation • …
• Lemma. k is a node in treap, then E max depth k O log N
Why we are using a treap? • Easy to understand • Easy to use • Well reliability • Average depth O(logN)
Thank you Q & A
Recommend
More recommend