Professional Documents
Culture Documents
Dynamic Sets
Dynamic Sets
Data Structures for Dynamic Sets • INSERT (S, x) adds element pointed to by x to S
Algorithms operate on data, which can be thought of as forming a • DELETE (S, x) removes element pointed to by x from S
set S. The data sets manipulated by algorithms are dynamic, • SEARCH (S, k) returns pointer to element x with key[x] = k (or
meaning they can grow, shrink, or otherwise change over time. returns nil)
• MINIMUM (S) returns element with the smallest key
Data Structures are structured ways to represent finite dynamic • MAXIMUM (S) returns element with the largest key
sets. Different data structures support different kinds of data • SUCCESSOR (S, x) returns element with the next key larger than
key[x]
manipulations, e.g., • PREDECESSOR (S, x) returns element with the next key smaller
§ dictionary: insert, delete, test for membership than key[x]
§ priority queue: insert, extract-max
Running Time of a dynamic set operation is usually measured in
terms of the size of the set (i.e., number of elements currently in
the set).
1 2
3 4
1
BST Succssor & Predecessor
BST Min & Max Tree-Successor( x)
o If x has a rightchild, then
The minimum element in a BST can always be found by successor(x) is the smallest 1. if right(x) ≠ NIL then
following left child pointers to a leaf (until a NIL left child node in the subtree rooted at 2. return Tree-Minimum(right[x])
pointer is encountered). Likewise, the maximum element can be
right(x). 3. temp ← parent[x]
o If x has no rightchild, then
found by following right child pointers to a leaf . successor(x) is the nearest
4. while (temp ≠ NIL and x = right(temp))
ancestor of x whose left 5. x ← temp
Tree-Minimum( x) Tree-Maximum( x) child is also an ancestor of x 6. temp ← parent[temp]
(or x itself) 7. return temp
1. while left[x] ≠ NIL do 1. while right[x] ≠ NIL do
2. x ← left[x] 2. x ← right[x] Tree-Predecessorr(x)
o If x has a leftchild, then
3. return x 3. return x 1. if left[x]≠ NIL then
predecessor(x) is the largest
node in the subtree rooted at 2. return Tree-Maximum(left[x])
left(x). 3. temp ← parent[x]
Both have running times of O(h), where h is the height of the o If x has no leftchild, then 4. while (temp ≠ NIL and x = left[temp]))
tree. predecessor(x) is the nearest
5. x ← temp
ancestor of x whose right
child is also an ancestor of x 6. temp ← parent[temp]
(or x itself) 7. return temp
7 8
18 22 temp 18 22 temp
25 16
17 19 21 25 16 17 19 21 25 25
14 23
temp 21 20 temp
15 22
17 19 22 24
17 19 19 20