firstmid

Transkript

firstmid
Datové struktury a algoritmy
Část 7
Vyhledávání a vyhledávací
stromy
Searching and Search Trees
Petr Felkel
7.12.2005
Searching (Vyhledávání)
Typical operations
Implementation in an array
•
•
Sequential search
Binary search
Binary search tree – BST (BVS)
•
•
•
DSA
Node representation
Operations
Tree balancing
2 / 95
Searching (Vyhledávání)
Input: a set of n keys, a query key q
Problem description: Where is q?
H
N
D
B
A
F
C
E
J
G
I
S
M
P
V
G?
DSA
3 / 95
Searching (Vyhledávání)
Input: a set of n keys, a query key q
Problem description: Where is q?
H
N
D
B
A
DSA
F
C
E
J
G
G
I
S
M
P
V
4 / 95
Searching (Vyhledávání)
Input: a set of n keys, a query key q
Problem description: Where is q?
H
N
D
B
A
F
C
E
J
G
I
S
M
P
V
L?
DSA
5 / 95
Searching (Vyhledávání)
Input: a set of n keys, a query key q
Problem description: Where is q?
H
N
D
B
A
F
C
E
J
G
I
S
M
P
V
L not found
DSA
6 / 95
Search space
min,max
empty
Search
space
Elem
search
getKey
Key
pred,
succ
insert,delete,replace
DSA
7 / 95
Searching (Vyhledávání)
Search space (lexicon)
DSA
•
Static
- fixed
•
Dynamic
- changes in time
-> simpler implementation
-> change means new release
-> more complex implementation
-> change by insert,delete,replace
8 / 95
Searching (Vyhledávání)
Operations:
k…key, e…element with key k
x…data set {subtree root node,
array, table,…}
Informal list:
DSA
•
•
•
search(x,k)
min(x), max(x)
pred(x,e), succ(x,e)
•
insert(x,e), delete(x,e),
replace(x,e)
9 / 95
Searching (Vyhledávání)
Typical operations
Implementation in
in an
an array
array
Implementation
•
•
Sequential search
Binary search
Binary search tree – BST (BVS)
•
•
•
DSA
Node representation
Operations
Tree balancing
10 / 95
Implementation
• Address search (přímý přístup)
•
•
Compute position from key
Array, table,…
pos = f(k)
• Associative search
•
DSA
Element located in relation to others
11 / 95
Implementation quality
• P(n) = memory complexity
• Q(n) = time complexity of search,
query
• I(n) time complexity of insert
• D(n) time complexity of delete
DSA
12 / 95
Searching (Vyhledávání)
Typical operations
Implementation
• In an array
•
•
Sequential search
Binary search
• Binary search tree – BST (BVS)
•
•
DSA
Node representation
Tree balancing
13 / 95
Searching in unsorted array
0 1
2
3
4
5
D B A C
size
Unsorted array
Sequential search Q(n) = O(n)
insert
I(n) = O(1)
delete
D(n) = O(n)
min, max
in O(n)
nodeT seqSearch( key k, nodeT a[] ) {
int i;
while( (i < a.size) && (a[i].key != k) )
i++;
if( i < a.size ) return a[i];
else return NODE_NOT_FOUND;
}
DSA
P(n) = O(n)
Java-like pseudo code
14 / 95
Searching in unsorted array
0 1
2
3
4
5
D B A C E
Unsorted array with sentinel
Sequential search still Q(n) = O(n)
size
search(“E“, a)
nodeT seqSearchWithSentinel( key k, nodeT a[] ) {
int i;
a[a.size] = createArrayElement( k ); // place a sentinel
while( a[i].key != k )
// and save one test
i++;
// per step
if( i < a.size ) return a[i];
else return NODE_NOT_FOUND;
}
Java-like pseudo code
DSA
15 / 95
Searching in sorted array
0 1
2
3
4
5
A B C E
size
Sorted array
Binary search Q(n) = O(log(n))
insert
I (n) = O(n)
delete
D(n) = O(n)
min, max
in O(1)
nodeT binarySearch( key k, nodeT sortedArray[] ) {
int pos = bs( k, sortedArray, 0, sortedArray.size - 1 );
if( pos >= 0 ) return sortedArray[pos];
else
return NODE_NOT_FOUND;
// -(pos+1) contains the position
// to insert the node with key k
}
Java-like pseudo code
DSA
16 / 95
Binary search
//Recursive version
int bs( key k, nodeT a[], int first, int last ) {
if( first > last ) return –(first + 1); // not found
int mid = ( first + last ) / 2;
if( k < a[mid].key ) return bs( k, a, first, mid – 1);
if( k > a[mid].key ) return bs( k, a, mid + 1, last );
return mid;
// found!
}
Java-like pseudo code
// Iterative version
int bs(key k, nodeT a[], int first, int last ) {
while (first <= last) {
int mid = (first + last) / 2; // compute the mid point
if (key > a[mid]) first = mid + 1;
else if (key < a[mid].key) last = mid - 1;
else return mid; // found it.
} return -(first + 1); // failed to find key
}
Java-like pseudo code
DSA
17 / 95
Searching (Vyhledávání)
Typical operations
Implementation in an array
•
•
Sequential search
Binary search
Binary search tree – BST (BVS)
•
•
•
DSA
Node representation
Operations
Tree balancing
18 / 95
Binární vyhledávací strom (BVS)
• Kořenový binární strom
•
uzel má 0, (1), 2 následníky
• Binární vyhledávací strom (BVS)
•
•
•
•
DSA
uspořádaný kořenový binární strom
pro všechny uzly uL z levého podstromu
platí: klíč(uL) < klíč(u)
pro všechny uzly uR z pravého podstromu
platí: klíč(uR) > klíč(u)
u je kořen
19 / 95
Binary Search Tree (BST)
• Rooted binary tree
•
node has 0, (1), 2 successors
• Binary Search Tree (BST)
•
•
•
•
DSA
Ordered rooted binary tree
for each node uL in the left sub-tree:
key(uL) < key(u)
for each node uR in the right sub-tree:
key(u) > key(uR)
u is the root
20 / 95
Binární vyhledávací strom
Binary Search Tree
=
7
<
>
9
2
<
1
DSA
<
>
5
8
<
>
3
6
>
10
21 / 95
Tree node representation
key
left right
• search
• min, max
DSA
key
key
left right
left right
22 / 95
Tree node representation
parent
key
left right
DSA
• search
• min, max
parent
parent
key
key
• predecessor,
left right
left right
successor
23 / 95
Tree node representation
public class Node {
public Node left;
public Node right;
public int key;
public Node(int k) {
key = k;
left = null;
right = null;
dat = …;
}
}
public class Tree {
public Node root;
public Tree() {
root = null;
See in Lesson6, page 17-18
}}
DSA
public class Node {
public Node parent;
public Node left;
public Node right;
public int key;
public Node(int k)
{
key = k;
parent = null;
left = null;
right = null;
dat = …;
}
}
24 / 95
Searching BST
G<H
H
N
D
G>D
B
F
J
S
G>F
A
C
E
G
I
M
P
V
G = G => stop, element found
DSA
25 / 95
Searching BST - recursively
Node TreeSearch( Node x, key k )
{
if(( x == null ) or ( k == x.key ))
return x;
if( k < x.key )
return TreeSearch( x.left, k );
else
return TreeSearch( x.right, k );
}
Java-like pseudo code
DSA
26 / 95
Searching BST - iteratively
Node TreeSearch( Node
{
while(( x != null )
{
if( k < x.key ) x
else
x
}
return x;
}
x, key k )
and (k != x.key ))
= x.left;
= x.right;
Java-like pseudo code
DSA
27 / 95
Minimum in BST
H
N
D
B
A
DSA
F
C
E
J
G
I
S
M
P
V
28 / 95
Minimum in BST - iteratively
Node TreeMinimum( Node x )
{
if( x == null ) return null;
while( x.left != null )
{
x = x.left;
}
return x;
}
Java-like pseudo code
DSA
29 / 95
Maximum in BST - iteratively
Node TreeMaximum( Node x )
{
if( x == null ) return null;
while( x.right != null )
{
x = x.right;
}
return x;
}
Java-like pseudo code
DSA
30 / 95
Maximum in BST
H
N
D
B
A
DSA
F
C
E
J
G
I
S
M
P
31 / 95
Successor in BST
1/4
in the sorted order (in-order tree walk)
Two cases:
1. Right son exists
2. Right son is null
DSA
32 / 95
Successor in BST
1/4
in the sorted order (in-order tree walk)
1. Right son exists
H
N
D
B
A
F
C
E
succ(B) -> C
succ(H) -> I
DSA
J
G
I
S
M
P
How?
33 / 95
Successor in BST
2/4
in the sorted order (in-order tree walk)
1. Right son exists
H
N
D
B
A
F
C
E
succ(B) -> C
succ(H) -> I
DSA
J
G
I
S
M
P
Find the minimum in the right tree
= min( x.right )
34 / 95
Successor in BST
3/4
in the sorted order (in-order tree walk)
2. Right son is null
H
N
D
B
A
F
C
E
succ(C) -> D
succ(G) -> H
DSA
J
G
I
S
M
P
How?
35 / 95
Successor in BST
4/4
in the sorted order (in-order tree walk)
2. Right son is null
x = node on path
H
y = its parent
N
D
y
x
B
A
C
E
succ(C) -> D
succ(G) -> H
DSA
F
J
G
I
S
M
P
Find the minimal parent to the right
(the minimal parent the node is left from)
36 / 95
Successor in BST - recursively
in the sorted order (in-order tree walk)
Node TreeSuccessor( Node x )
{ if( x == null ) return null;
if( x.right != null )
return TreeMinimum( x.right );
y = x.parent;
while( (y != null) and (x == y.right))
{ x = y;
y = x.parent; }
return y; }
Java-like pseudo code
DSA
37 / 95
Predecessor in BST - recursively
in the sorted order (in-order tree walk)
Node TreePredecessor( Node x )
{ if( x == null ) return null;
if( x.left != null )
return TreeMaximum( x.right );
y = x.parent;
while( (y != null) and (x == y.left))
{ x = y;
y = x.parent; }
return y; }
Java-like pseudo code
DSA
38 / 95
Operational Complexity
The following dynamic-set operations:
Search,
Maximum, Minimum,
Successor, Predecessor
can run in O(h) time
on a binary tree of height h. …. what h?
DSA
39 / 95
Operational Complexity
A
H
B
C
N
D
D
E
B
F
J
S
F
G
H
A
DSA
C
E
G
I
M
P
I
V
J
h = log2(n)
h = n!!!
O(log(n))
O(n)!!!
=> balance the tree!!!
40 / 95
M
Operational Complexity
The following dynamic-set operations:
Search,
Maximum, Minimum,
Successor, Predecessor
can run in Ω(nlog(n)) and O(n) time
on a not-balanced binary tree with n nodes.
DSA
41 / 95
Insert (vložení prvku)
H
L>H
D
L<N
B
A
F
C
E
J
G
x = node on path
I
y = its parent
N
y
M
S
x
P
V
insert L
1. find the parent leaf
2. connect new element as a new leaf
DSA
42 / 95
Insert (vložení prvku)
void treeInsert( Tree t, Elem e )
{
x = t.root; y = null;
// t is tree root
if( x == null ) t.root = e;
else {
while(x != null) {
// find the parent leaf
y = x;
if( e.key < x.key ) x = x.left;
else x = x.right;
}
// add new to parent
if( e.key < y.key ) y.left = e;
else y.right = e;
}
Java-like pseudo code
DSA
43 / 95
Delete (odstranění prvku)
a) delete a leaf (smaž list)
H
H
N
D
B
A
F
C
E
J
G
I
S
M
P
N
D
delete(G)
B
V
A
F
C
E
J
I
S
M
P
V
e=y
leaf has no children -> it is simply removed
DSA
44 / 95
Delete (odstranění prvku)
b) with one child (vnitřní s potomkem)
H
H
N
D
B
A
F
C
E
e=y
x
J
I
S
M
P
B
V
A
N
D
delete(F)
E
C
J
I
S
M
P
node has one child -> splice the node out
(přemosti)
DSA
45 / 95
V
Delete (odstranění prvku)
c) with two children (se 2 potomky)
H
e
F
N
D
B
A
F
C
E
x
y
J
I
S
M
P
B
V
A
N
D
delete(H)
E
C
J
I
S
M
P
node has two children -> replace it with a
predecessor (or successor) with max one child
DSA
46 / 95
V
Delete (odstranění prvku)
Node treeDelete( Tree t, Node e
)
{ Node x, y;
// e..node
to delete
// find node y to splice out
if(e.left == null OR e.right
H
== null)
H e
H
D
D
y = e; D
// case a,b)
0 to 1 child
B
F
B
F y
B
F y=e
else
// case c) 2 children
A C E x
A C E G y=e
A C E
ya) = TreePredecessor(e);
b)
C)
DSA
47 / 95
Delete (odstranění prvku)
...
// find y’s only child x
if( y.left != null )
x = y.left;
// non-null child of y or null
else x = y.right;
... //(y will be physically removed)
H
H
D
D
B
A
F
C
E
B
G
a)
DSA
H
y=e
A C E
e
D
F
x
b)
y=e
B
A
F
C
E
y
x
C)
48 / 95
Delete (odstranění prvku)
...
// link x with parent of y – link up
if( x != null ) x.parent = y.parent;
...
H
H
D
D
B
A
F
C
E
B
G
a)
DSA
H
y=e
A C E
e
D
F
x
b)
y=e
B
A
F
C
E
y
x
C)
49 / 95
Delete (odstranění prvku)
... // link x with parent of y - link down
if( y.parent == null )
E x
F y
t.root = x // it was root
else if( y == (y.parent).left ) E x
(y.parent).left = x;
else
(y.parent).right = x;
...
H
H
D
D
B
A
F
C
E
a)
DSA
H
Link to
null
G y=e
B
A C E
e
D
F
x
b)
y=e
B
A
F
C
E
y
x
C)
50 / 95
Delete (odstranění prvku)
...
if( y != e )
// replace e with in-order successor
{
e.key = y.key; // copy the key
e.dat = y.dat; // copy other fields too
}
return y;
H e
F e
// To be disposed
D
D
// or reused
B
F y
B
E y
// outside
}
DSA
A
C
E
x
A
C
51 / 95
And the operational
complexity?
Operational Complexity
A
H
B
C
N
D
D
E
B
F
J
S
F
G
H
A
DSA
C
E
G
I
M
P
I
V
J
h = log2(n)
h = n !!!
O(log(n))
O(n) !!!
=> balance the tree!!!
53 / 95
M
Searching (Vyhledávání)
Typical operations
Implementation in an array
•
•
Sequential search
Binary search
Binary search tree – BST (BVS)
•
•
•
DSA
Node representation
Operations
Tree balancing
balancing
Tree
54 / 95
Tree balancing
• Balancing criteria
• Rotations
• AVL – tree
• Weighted tree
DSA
55 / 95
Tree balancing
Why?
To get the O(log n) complexity of
search,...
How?
By local modifications reach the
global goal
DSA
56 / 95
Vyvažování stromu
• Silná podmínka (Ideální případ)
Pro všechny uzly platí:
počet uzlů vlevo = počet uzlů vpravo
• Slabší podmínka
•
•
•
DSA
výška podstromů - AVL strom
výška + počet potomků - 1-2 strom, ...
váha podstromů (počty uzlů) - váhově
vyvážený strom
57 / 95
Tree balancing
• Strong criterion (Ideal case)
For all nodes:
No of nodes left = No of nodes right
• Weaker criterion
•
•
•
DSA
subtree heights - AVL tree
height + number of children - 1-2 tree, ...
subtree weights (No of nodes) - weighted
tree
58 / 95
Tree balancing
• Balancing criteria
• Rotations
• AVL – tree
• Weighted tree
DSA
59 / 95
Levá rotace (Left rotation)
root
p1
B
A
x
y
z
II
A
h-1
h
h+1
B
I
z
x
y
Node leftRotation( Node root ) {
// subtree root node !!!
if( root == null ) return root;
Node p1 = root.right;
(init)
if (p1 == null) return root;
root.right = p1.left;
(I)
p1.left
= root;
(II)
return p1;
}
Java-like pseudo code
DSA
60 / 95
Pravá rotace (right rotation)
root
p1
A
A
B
I
z
x
II
y
h-1
h
h+1
B
x
y
z
Node rightRotation( Node root ) { // subtree root node !!!
if( root == null ) return root;
Node p1 = root.left;
(init)
if (p1 == null) return root;
root.left = p1.right;
(I)
p1.right = root;
(II)
return p1;
}
Java-like pseudo code
DSA
61 / 95
LR rotace (left-right rotation)
root
p1
A
1
w
x
C
IV
A
2
p2 z
B
y
h-1
h
B
II
III
I
x
y
C
w
h+1
Node leftRightRotation( Node root ) { if(root==null)....;
Node p1 = root.left; Node p2 = p1.right;
(init)
root.left = p2.right;
(I)
p2.right = root;
(II)
p1.right = p2.left;
(III)
p2.left = p1;
(IV)
return p2;
}
Java-like pseudo code
DSA
62 / 95
z
RL rotace (right- left rotation)
root
p1
C
A
2
w p2
B
x
1
y
II
A
h-1
z
h
w
B
IV
I
III
x
y
C
z
h+1
Node rightLeftRotation( Node root ) { if(root==null)....;
Node p1 = root.right; Node p2 = p1.left;
(init)
root.right = p2.left;
(I)
p2.left = root;
(II)
p1.left = p2.right;
(III)
p2.right = p1;
(IV)
return p2;
}
Java-like pseudo code
DSA
63 / 95
Tree balancing
• Balancing criteria
• Rotations
• AVL tree
• Weighted tree
DSA
64 / 95
Kdy použijeme kterou rotaci?
• AVL strom [Richta90]
•
•
•
•
DSA
Výškově vyvážený strom
Georgij Maximovič Adelson-Velskij a
Evgenij Michajlovič Landis
Výška:
•
•
Prázdný strom: výška = -1
neprázdný: výška = výška delšího potomka
Vyvážený strom:
rozdíl výšek potomků bal = {-1, 0, 1}
65 / 95
AVL strom (AVL tree)
// An inefficient recursive definition
int height( Node t )
{
if( t == null )
return -1;
else
return 1 + max(
}
height( t.left ),
height( t.right ) );
int bal( Node t )
{
return height( t.left ) - height( t.right );
}
Java-like pseudo code
DSA
66 / 95
AVL strom - výšky a rozvážení
AVL tree - heights and balance
-1
2
1
1
0
-1
0
0
-1
-1
-1
výška / height
DSA
0
2
1
1
rozvážení/ balance 0
0
-1 -1
2
0
0
0
3
0
-1
0
0
1
0
0
0 -1 -1 -1 -1 0
0
0
-1 -1 -1 -1
0
0
-1
0
0
-1 -1
67 / 95
-1
AVL strom před vložením uzlu
AVL tree before node insertion
-1
2
1
1
0
-1
2
0
0
0
0
0
-1
-1
2
0
-1
0
0
-1 -1
-1
0
1
-1
DSA
0
1
0
-1 -1
3
0
1
0
0
0 -1 -1 -1 -1 0
0
-1
-1
0
0
0
-1 -1
68 / 95
0
-1
AVL strom - nejmenší podstrom
AVL tree - the smallest subtree
Nejmenší podstrom, který se přidáním uzlu rozváží
The smallest sub-tree looses its balance by insertion
1
1
0
0
0
0
-1
DSA
0
-1
0
-1
0
-1 -1
-1
69 / 95
AVL tree
Node insertion – an example
DSA
70 / 95
AVL strom - vložení uzlu doleva
AVL tree - node insertion left
a) Podstrom se přidáním uzlu doleva rozváží
The sub-tree loses its balance by node insertion - left
1
1
2
0
0
0
-1
2
0
0
-1
0
1
1
-1
insert left
0
-1 -1
1
-1
0
0
0
0
-1
-1
0
-1 -1
-1
0
DSA
71 / 95
AVL strom - pravá rotace
AVL tree - right rotation
a) Vložen doleva => korekce pravou rotací
Node inserted to the left => balance by right rotation
B
2
A
1
1
0
1
1
0
2
0
0
-1
-1
1
-1
0
-1
R rot
0
0
0
-1
B
0
1
0
-1 -1
0
A
0
0
-1
-1
-1
0
DSA
72 / 95
-1
-1
AVL strom - vložení uzlu doprava
AVL tree after insertion-right
b) Podstrom se přidáním uzlu doprava rozváží
The sub-tree loses its balance by node insertion - right
1
1
0
0
-1
2
0
0
0
-1
0
0
-1
insert right
0
-1
0
-1
0
-1 -1
2
-1
0
1
-1
-1
-1 -1
0
-1
DSA
-1
0
-1
73 / 95
AVL strom - pravá rotace
AVL tree - right rotation
b) Vložen doprava => korekce LR rotací
Node inserted right => balance by the LR rotation
C
2
2
A
2
-1
0
1
1
0
-1
-1
-1 -1
1
0
0
-1
B
A
0
-1
0
-1
-1
0
-1
0
DSA
C
0
0
0
-1
0
1
1
0
-1
LR rot
0
B
74 / 95
-1
-1
AVL tree
Node insertion - in general
DSA
75 / 95
AVL strom - nejmenší podstrom
AVL tree - the smallest subtree
Nejmenší podstrom, který se přidáním uzlu rozváží
The smallest sub-tree looses its balance by insertion
n+1
1
0
n
0
n
n
DSA
n
n
n
n
Node with balance 0
Sub-tree of height n
n Sub-tree below of
height n
76 / 95
AVL strom - vložení uzlu doleva
AVL tree - node insertion left
a) Podstrom se přidáním uzlu doleva rozváží
The sub-tree loses its balance by node insertion - left
B
1
n+1
A
n
B
n+2
n
A
0
n
n
2
n
1
n+1
n
n
n
n
insert left
n
n
0
DSA
77 / 95
AVL strom - pravá rotace
AVL tree - right rotation
a) Vložen doleva => korekce pravou rotací
Node inserted to the left => balance by right rotation
B
n+2
A
n+1
2
A
n
n+1
n+1
B
1
n
n
0
n
n
0
n
n
0
DSA
n
n
R rot
n
0
78 / 95
AVL strom - vložení uzlu doprava
AVL tree after insertion-right
b1) Podstrom se přidáním uzlu doprava rozváží
The sub-tree loses its balance by node insertion - right
C
n+1
A
C
n+2
n
A
0
n
n
B
n-1
n
1
n-1
0
n
n
n-1
n-1
insert right
n
2
n
-1
n+1
B
1
n
n-1
n-1
n
n-1
0
DSA
79 / 95
AVL strom - pravá rotace
AVL tree - right rotation
b1) Vložen doprava => korekce LR rotací
Node inserted right => balance by the LR rotation
C
2
n+2
A
n
n
-1
n+1
A
2
n+1
B
1
1
n
n-1
n-1
n
n-1
n
0
n
n
n-1
LR rot
n
B
0
n+1
-1
n-1
n
n-1
n
0
0
DSA
C
80 / 95
AVL strom - pravá rotace
AVL tree - right rotation
b2) Vložen doprava => korekce LR rotací
Node inserted right => balance by the LR rotation
C
2
n+2
A
n
n
-1
n+1
A
2
n+1
B
1 -1
n
n-1
n-1
n
n-1
n
1
n-1
n
n-1
LR rot
n
B
0
n+1
0
n
n
n-1
0
0
DSA
C
81 / 95
n
BST Insert without balancing
avlTreeInsert( Tree t, Elem e )
{
x = t.root; y = null;
if( x == null ) t.root = e;
else {
while(x != null) {
// find the parent leaf
y = x;
if( e.key < x.key ) x = x.left
else x = x.right
}
// add new to parent
if( e.key < y.key ) y.left = e
else y.right = e
}
Java-like pseudo code
DSA
82 / 95
AVL Insert (with balancing)
avlTreeInsert( tree t, elem e )
{
// init
// 1. find a place for insert
// 2. if( already present )
//
replace the node
// else
//
insert new node
//
3.balance the tree, if necessary
}
Java-like pseudo code
DSA
83 / 95
AVL Insert - variables & init
avlTreeInsert( Tree t, Elem e )
{
Node cur, fcur; // current sub-tree and its father
Node a, b; // smallest unbalanced tree and its son
Bool found; // node with the same key as e found
Node help;
// init
found = false;
cur = t.root; fcur = null;
a = cur, b = null;
// 1. find a place for insert
...
Java-like pseudo code
DSA
84 / 95
AVL Insert - find place for insert
...
// 1. find a place for insert
while(( cur != null ) and !found )
{
if( e.key == cur.key ) found = true;
else {
if( e.key < cur.key ) help = cur.left;
else help = cur.right;
if(( help != null) and ( bal(help) != 0 )){
//remember possible place for unbalance
a = help;
}
fcur = cur; cur = help;
}
} ...
DSA
85 / 95
AVL Insert - replace or insert new
...
// 2. if( already present ) replace the node value
if( found )
setinfo( cur, e );
// replace the node value
else {
// insert new node to fcur
help = leaf( e );
// cons ( e, null, null );
if( fcur == null ) t.root = help;
// new root
else {
if( e.key < fcur.key )
fcur.left = help;
else
fcur.right = help;
}
...
DSA
86 / 95
AVL Insert - balance the subtree
... // !found continues
// 3.balance tree, if necessary
if( bal(a) == 2 )
{
// inserted left
b = a.left;
if( b.key < e.key ) //and right from
a.left = leftRotation( b );
a = rightRotation( a );
}
else if( bal(a) == -2){ //inserted right
b = a.right;
if( e.key < b.key )
// and left from
a.right = rightRotation( b );
a = leftRotatation( a );
} // else tree remained balanced
} // !found
from 1
its son
from -1
its son
}
DSA
87 / 95
AVL - výška stromu
For AVL tree S with n nodes holds
Height h(S) is at maximum 45% higher in
comparison to ideally balanced tree
log2(n+1) ≤ h(S) ≤ 1.4404 log2(n+2)-0.328
[Hudec96], [Honzík85]
DSA
88 / 95
Tree balancing
• Balancing criteria
• Rotations
• AVL tree
• Weighted tree
DSA
89 / 95
Váhově vyvážené stromy
Weight balanced trees
(stromy s ohraničeným vyvážením)
Váha uzlu u ve stromě S:
v (u) = 1/2,
když je u listem
v (u) = ( |UL| + 1) / ( |U| + 1 ),
když u je kořen podstromu SU⊆ S
UL = množina uzlů levého podstromu SU
U = množina uzlů podstromu SU
DSA
90 / 95
Váhově vyvážené stromy
Weight balanced trees
Stromy s ohraničeným vyvážením α:
Strom S má ohraničené vyvážení α, 0 ≤ α ≤ 0,5,
jestliže pro všechny uzly S platí
α ≤ v(u) ≤ 1- α
Výška h(S) stromu S s ohraničeným vyvážením α
h(S) ≤ (1 + log2(n+1) - 1) / log2 (1 / (1- α))
[Hudec96], [Mehlhorn84]
DSA
91 / 95
Weight balanced tree example
(5+1) / (12+1)
= 6/13
H
(3+1) / (5+1)
= 2/3
(1+1) / (3+1)
= 1/2
(3+1) / (6+1)
= 4/7
N
D
B
F
1/2
(1+1) / (2+1)
= 2/3
J
S
1/2
A
(0+1) / (1+1)
= 1/2
DSA
C
I
M
P
1/2
1/2
1/2
1/2
92 / 95
Levá rotace (Left rotation) [Hudec96]
VB ’
VA
A
VB
B
VA’
B
A
x
z
y
z
x
y
VA’ = VA / ( VA + (1- VA) . VB)
VB’ = VA + (1- VA) . VB
DSA
93 / 95
RL rotace (right- left rotation)
VA
A
C
2
w
VB
B
x
VC
VB ’
A
VA’
B
VC ’
C
1
y
z
w
x
y
z
VA’ = VA / ( VA + (1- VA) VB VC)
VB’ = VB (1- VC) / (1- VB VC)
VC’ = VA + (1- VA) . VA VB
DSA
[Hudec96]
94 / 95

Podobné dokumenty

2.část - Skolamarket

2.část - Skolamarket 1) Nebudu se dotýkat poškozeného kabelu nebo elektrického přístroje. 2) Nebudu se dotýkat elektrického přístroje mokrýma nebo vlhkýma rukama. 3) Nebudu dělat žádné pokusy s proudem ze zásuvky. 4) N...

Více

Ridici jednotka Multi-control Duo - obsluha

Ridici jednotka Multi-control Duo - obsluha Dodržujte existující bezpečnostní předpisy a bezpečnostní pokyny lokálních dodavatelů energie. Pokud otevřete jednotku (odstraníte kryt nebo víko jednotky), nebo když pracujete u čerpadla, nebo s č...

Více

Diplomová práce

Diplomová práce S psychospirituální krizí hodně souvisí a proto mi připadá důležité přiblížit je dříve, než začnu psát přímo o psychospirituální krizi. Následně se pokusím definovat psychospirituální krizi a objas...

Více

IAJCE Přednáška č. 10 1 každému znaku je nutné přiřadit

IAJCE Přednáška č. 10 1 každému znaku je nutné přiřadit o Horních 128 bytů znaky národních abeced Problém špatně zvoleného kódování nefunkční znaky z horní poloviny tabulky o text v ISO8859-2 zobrazený jako Win1250

Více

Seznam všech témat pro ústní zkoušku PRG+IDS 2011

Seznam všech témat pro ústní zkoušku PRG+IDS 2011 • jazyk SQL – jazyk pro dorozumívání klienta se serverem • dělení: DDL, DML a DCL • příkazy pro změny struktury a obsahu tabulek • struktura SQL příkazu SELECT • zálohování a načítání dat ze soubor...

Více

prodej zemědělské techniky

prodej zemědělské techniky zápis zájemců a vydání čísel

Více

dsj2

dsj2 binární strom - má 0, (1), 2 následníky uspořádaný binární strom - dvojice a jsou uspořádány

Více

AMX Mod X

AMX Mod X www.n1ce.cz – GAMEHOSTING & WEBHOSTING Statická IP adresa: otevřeme si soubor usere.ini, který najdeme na FTP svého serveru cstrike/addons/amxmodx/configs, tento soubor si otevřeme v poznámkovém b...

Více