KEMBAR78
Trees, Binary Search Tree, AVL Tree in Data Structures | PDF
SUYASH BHARDWAJ
FACULTY OF ENGINEERING AND TECHNOLOGY
GURUKUL KANGRI VISHWAVIDYALAYA, HARIDWAR
Data
Structures
Primitive
Int
Char
Float
Pointer
Non -
Primitive
Linear
Arrays
Stacks
Queues
Non
Linear
Graphs
Trees
Linked
lists
Files
Data
Structures
Primitive
Int
Char
Float
Pointer
Non -
Primitive
Linear
Arrays
Stacks
Queues
Non
Linear
Graphs
Trees
Linked
lists
Files
Binary Tree Representation
 Array representation.
 Linked representation.
Array Representation
 Number the nodes using the numbering scheme for a
full binary tree. The node that is numbered i is stored in
tree[i].
tree[]
0 5 10
a b c d e f g h i j
b
a
c
d e f g
h i j
1
2 3
4 5 6 7
8 9 10
Right-Skewed Binary Tree
 An n node binary tree needs an array whose
length is between n+1 and 2n.
a
b
1
3
c
7
d
15
tree[]
0 5 10
a - b - - - c - - - - - - -
15
d
Linked Representation
 Each binary tree node is represented as an object
whose data type is BinaryTreeNode.
 The space required by an n node binary tree is n *
(space required by one node).
typedef struct node
{
int data;
struct node *lc,*rc;
};
Link Representation
of Binary Tree
Linked Representation Example
a
b
rightChild
root
f
c
d e
g
h
leftChild
TREE
 A tree is a hierarchical representation of a finite set of one
or more data items such that:
• There is a special node called the root of the tree.
• The nodes other than the root node form an ordered pair of disjoint
subtrees.
Level 0
Level 1
Level 2
Root
Leaf
LeafLeaf
Binary Tree
Binary Tree
Binary Tree is a rooted tree in which
root can have maximum two children
such that each of them is again a binary
tree. That means, there can be 0,1, or 2
children of any node.
Strict Binary Tree
Strict Binary Tree
Strict Binary Tree is a Binary tree in
which root can have exactly two
children or no children at all. That
means, there can be 0 or 2 children of
any node.
Complete Binary Tree
Complete Binary Tree
Complete Binary Tree is a Strict Binary
tree in which every leaf node is at same
level. That means, there are equal
number of children in right and left
subtree for every node.
Extended Binary Tree
 A binary tree with special nodes replacing every null
subtree. Every regular node has two children, and
every special node has no children.
Extended Binary Tree
 An extended binary tree is a transformation of
any binary tree into a complete binary tree.
 This transformation consists of replacing every null
subtree of the original tree with “special nodes.”
 The nodes from the original tree are then called as
internal nodes, while the “special nodes” are called as
external nodes.
Tree Traversal : Pre order
 Pre order (N L R)
Tree Traversal : Pre order
 Pre order (N L R)
A
Tree Traversal : Pre order
 Pre order (N L R)
A, B
Tree Traversal : Pre order
 Pre order (N L R)
A, B, D
Tree Traversal : Pre order
 Pre order (N L R)
A, B, D, E
Tree Traversal : Pre order
 Pre order (N L R)
A, B, D, E, C
Tree Traversal : Pre order
 Pre order (N L R)
A, B, D, E, C, F
Tree Traversal : Pre order
 Pre order (N L R)
A, B, D, E, C, F, G
Tree Traversal : In order
 In order (L N R)
Tree Traversal : In order
 In order (L N R)
D
Tree Traversal : In order
 In order (L N R)
D, B
Tree Traversal : In order
 In order (L N R)
D, B, E
Tree Traversal : In order
 In order (L N R)
D, B, E, A
Tree Traversal : In order
 In order (L N R)
D, B, E, A, F
Tree Traversal : In order
 In order (L N R)
D, B, E, A, F, C
Tree Traversal : In order
 In order (L N R)
D, B, E, A, F, C, G
Tree Traversal : Post order
 Post order (L R N)
Tree Traversal : Post order
 Post order (L R N)
D
Tree Traversal : Post order
 Post order (L R N)
D, E
Tree Traversal : Post order
 Post order (L R N)
D, E, B
Tree Traversal : Post order
 Post order (L R N)
D, E, B, F
Tree Traversal : Post order
 Post order (L R N)
D, E, B, F, G
Tree Traversal : Post order
 Post order (L R N)
D, E, B, F, G, C
Tree Traversal : Post order
 Post order (L R N)
D, E, B, F, G, C, A
Constructing Binary Tree
 In order – D, G, B, H, E, A, F, I, C
 Pre order – A, B, D, G, E, H, C, F, I
 Step 1 : finding the root
 Root Node – A (from pre order)
 Step 2 : Find left and right part of the root
 Left part -
 Right part -
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Binary Search Tree
The value at any node,
• Greater than every value in left subtree
• Smaller than every value in right subtree
– Example
• Y > X
• Y < Z Y
X Z
Binary Search Tree
• Values in left sub tree less than parent
• Values in right sub tree greater than parent
• Fast searches in a Binary Search tree, maximum of log
n comparisons
31
21 40
10 22 35 42
• Examples
Binary search
trees
Not a binary
search tree
5
10
30
2 25 45
5
10
45
2 25 30
5
10
30
2
25
45
Binary Search Trees
• search (root, 25 )
5
10
30
2 25 45
5
10
30
2
25
45
10 < 25, right
30 > 25, left
25 = 25, found
5 < 25, right
45 > 25, left
30 > 25, left
10 < 25, right
25 = 25, found
Example Binary Searches
Algorithm for Binary Search Tree
 A) compare ITEM with the root node N of the tree
 i) if ITEM<N, proceed to the left child of N.
 ii) if ITEM>N, proceed to the right child of N.
 B) repeat step (A) until one of the following occurs
 i) we meet a node N such that ITEM=N, i.e. search is
successful.
 ii) we meet an empty sub tree, i.e. the search is
unsuccessful.
typedef struct node
{
int data;
struct node *lc,*rc;
};
Binary Tree Implementation
search()
{
while (n != NULL)
{
if (n->data == item) // Found it
return n;
if (n->data > item) // In left subtree
n = n->lc;
else // In right subtree
n = n->rc;
}
return null;
}
Iterative Search of Binary Search Tree
Search(node *n, info)
{
if (n == NULL) // Not found
return( n );
else if (n->data == item) // Found it
return( n );
else if (n->data > item) // In left subtree
return search( n->left, item );
else // In right subtree
return search( n->right, item );
}
Recursive Search of Binary Search Tree
Insertion in a Binary Search Tree
• Algorithm
1. Perform search for value X
2. Search will end at node Y (if X not in tree)
3. If X < Y, insert new leaf X as new left subtree
for Y
4. If X > Y, insert new leaf X as new right subtree
for Y
• Insert ( 20 )
5
10
30
2 25 45
10 < 20, right
30 > 20, left
25 > 20, left
Insert 20 on left
20
Insertion in a Binary Search Tree
40
Insertion in a Binary Tree
40, 60, 50, 33, 55, 11
40
Insertion in a Binary Tree
40, 60, 50, 33, 55, 11
60
40
Insertion in a Binary Tree
40, 60, 50, 33, 55, 11
60
50
40
Insertion in a Binary Tree
40, 60, 50, 33, 55, 11
60
50
33
40
Insertion in a Binary Tree
40, 60, 50, 33, 55, 11
60
50
33
55
40
Insertion in a Binary Tree
40, 60, 50, 33, 55, 11
60
50
33
55
11
Deletion in Binary Tree
• Algorithm
1. Perform search for value X
2. If X is a leaf, delete X
3. Else //we must delete internal node
a) Replace with largest value Y on left subtree
OR smallest value Z on right subtree
b) Delete replacement value (Y or Z) from subtree
Note :-
– Deletions may unbalance tree
Example Deletion (Leaf)
• Delete ( 25 )
5
10
30
2 25 45
10 < 25, right
30 > 25, left
25 = 25, delete
5
10
30
2 45
Example Deletion (Internal Node)
• Delete ( 10 )
5
10
30
2 25 45
5
5
30
2 25 45
2
5
30
2 25 45
Replacing 10
with largest
value in left
subtree
Replacing 5
with largest
value in left
subtree
Deleting leaf
Example Deletion (Internal Node)
• Delete ( 10 )
5
10
30
2 25 45
5
25
30
2 25 45
5
25
30
2 45
Replacing 10
with smallest
value in right
subtree
Deleting leaf Resulting tree
Binary Search Properties
• Time of search
– Proportional to height of tree
– Balanced binary tree
• O( log(n) ) time
– Degenerate tree
• O( n ) time
• Like searching linked list / unsorted array
AVL Tree
 AVL trees are height-balanced binary search trees
 Balance factor of a node=
height(left sub tree) - height(right sub tree)
 An AVL tree has balance factor calculated at every node
 For every node, heights of left and right sub tree can
differ by no more than 1
 Store current heights in each node
AVL Tree
 A binary tree in which the difference of height of the
right and left subtree of any node is less than or equal
to 1 is known as AVL Tree.
 Height of left subtree – height of right subtree
can be either -1,0,1
AVL Tree
0 0 0
0
AVL Tree
1
0-1
0 1 0 0
0
Balanced as LST-RST=1
3 2
Insertion in AVL Tree
Case 1: the node was either left heavy or right heavy
and has become balanced
Insertion in AVL Tree
Case 2: the node was balanced and has now become
left or right heavy
Insertion in AVL Tree
Case 3: the node was heavy and the new node has been inserted in
the heavy sub tree thus creating an unbalanced sub tree
3
2
Rebalancing
• When the tree structure changes (e.g., insertion or
deletion), we need to transform the tree to restore the
AVL tree property.
• This is done using single rotations or double rotations.
Rotations
• single rotations
x
y
A
B
C
y
x
A
B C
Before Rotation After Rotation
e.g. Single Rotation
• Since an insertion/deletion involves
adding/deleting a single node, this can
only increase/decrease the height of some
subtree by 1
• Thus, if the AVL tree property is violated
at a node x, it means that the heights of
left(x) and right(x) differ by exactly 2.
• Rotations will be applied to x to restore
the AVL tree property.
Rotations
The new item is inserted in the subtree A.
The AVL-property is violated at x
height of left(x) is h+2
height of right(x) is h.
Single Rotation
Single rotation takes O(1) time.
Insertion takes O(log N) time.
The new item is inserted in the subtree C.
The AVL-property is violated at x.
Single Rotation
The new key is inserted in the subtree B1 or B2.
The AVL-property is violated at x.
x-y-z forms a zig-zag shape
also called left-right rotate
Double Rotation
The new key is inserted in the subtree B1 or B2.
The AVL-property is violated at x.
also called right-left rotate
Double Rotation
Insert 3,2,1,4,5,6,7
3
Example
3
2
Example
Insert 3,2,1,4,5,6,7
3
2
Example
1
Insert 3,2,1,4,5,6,7
3
2
Example
1
Single rotation
Insert 3,2,1,4,5,6,7
2
1
3
Example
Insert 3,2,1,4,5,6,7
2
1
3
Example
4
Insert 3,2,1,4,5,6,7
2
1
3
Example
4
5
Insert 3,2,1,4,5,6,7
2
1
3
Example
4
5
Single rotation
Insert 3,2,1,4,5,6,7
2
1
4
Example
53
Insert 3,2,1,4,5,6,7
2
1
4
Example
53
6
Insert 3,2,1,4,5,6,7
2
1
4
Example
53
6
Single rotation
Insert 3,2,1,4,5,6,7
4
2
5
Example
631
Insert 3,2,1,4,5,6,7
4
2
5
Example
631
7
Insert 3,2,1,4,5,6,7
4
2
5
Example
631
7
Single rotation
Insert 3,2,1,4,5,6,7
4
2
6
Example
731 5
Insert 3,2,1,4,5,6,7
j
k
X Y
Z
Consider a valid
AVL subtree
AVL Insertion: Outside Case
h
h
h
j
k
X
Y
Z
Inserting into X
destroys the AVL
property at node j
AVL Insertion: Outside Case
h
h+1 h
j
k
X
Y
Z
Do a “right rotation”
AVL Insertion: Outside Case
h
h+1 h
j
k
X
Y
Z
Do a “right rotation”
Single right rotation
h
h+1 h
j
k
X Y Z
“Right rotation” done!
(“Left rotation” is mirror
symmetric)
Outside Case Completed
AVL property has been restored!
h
h+1
h
j
k
X Y
Z
AVL Insertion: Inside Case
Consider a valid
AVL subtree
h
hh
Inserting into Y
destroys the
AVL property
at node j
j
k
X
Y
Z
AVL Insertion: Inside Case
Does “right rotation”
restore balance?
h
h+1h
j
k
X
Y
Z
“Right rotation”
does not restore
balance… now k is
out of balance
AVL Insertion: Inside Case
h
h+1
h
Consider the structure
of subtree Y… j
k
X
Y
Z
AVL Insertion: Inside Case
h
h+1h
j
k
X
V
Z
W
i
Y = node i and
subtrees V and W
AVL Insertion: Inside Case
h
h+1h
h or h-1
j
k
X
V
Z
W
i
AVL Insertion: Inside Case
We will do a left-right
“double rotation” . . .
j
k
X V
Z
W
i
Double rotation : first rotation
left rotation complete
j
k
X V
Z
W
i
Double rotation : second rotation
Now do a right rotation
jk
X V ZW
i
Double rotation : second rotation
right rotation complete
Balance has been
restored
hh h or h-1
B-Tree
All leaves are on the bottom level.
All internal nodes (except perhaps the root node) have at
least cell(m / 2) (nonempty) children.
The root node can have as few as 2 children if it is an
internal node, and can obviously have no children if the
root node is a leaf (that is, the whole tree consists only of
the root node).
Each leaf node (other than the root node if it is a leaf) must
contain at least ceil(m / 2) - 1 keys.
B-tree is a fairly well-balanced tree.
Let's work our way through an example similar to that given
by Kruse. Insert the following letters into what is originally
an empty B-tree of order 5:
C N G A H E K Q M F W L T Z D P R X Y S
Order 5 means that a node can have a maximum of 5
children and 4 keys. All nodes other than the root must
have a minimum of 2 keys. The first 4 letters get inserted
into the same node, resulting in this picture:
When we try to insert the H, we find no room in this node, so we
split it into 2 nodes, moving the median item G up into a new root
node. Note that in practice we just leave the A and C in the current
node and place the H and N into a new node to the right of the old
one.
Inserting E, K, and Q proceeds without requiring any splits:
H E K Q M F W L T Z D P R X Y S
Inserting M requires a split. Note that M happens to be the
median key and so is moved up into the parent node.
The letters F, W, L, and T are then added without needing any
split.
M F W L T Z D P R X Y S
When Z is added, the rightmost leaf must be split. The median item T is moved
up into the parent node. Note that by moving up the median key, the tree is kept
fairly balanced, with 2 keys in each of the resulting nodes.
The insertion of D causes the leftmost leaf to be split. D happens to be the median
key and so is the one moved up into the parent node. The letters P, R, X, and Y are
then added without any need of splitting:
Z D P R X Y S
Finally, when S is added, the node with N, P, Q, and R splits, sending
the median Q up to the parent. However, the parent node is full, so
it splits, sending the median M up to form a new root node. Note
how the 3 pointers from the old parent node stay in the revised node
that contains D and G.
HEAP
A max tree is a tree in which the key value in each node is no
smaller than the key values in its children. A max heap is a
complete binary tree that is also a max tree.
A min tree is a tree in which the key value in each node is no
larger than the key values in its children. A min heap is a
complete binary tree that is also a min tree.
Operations on heaps:
- creation of an empty heap
- insertion of a new element into the heap;
- deletion of the largest element from the heap
14
12 7
810 6
9
6 3
5
30
25
[1]
[2] [3]
[5] [6]
[1]
[2] [3]
[4]
[1]
[2]
2
7 4
810 6
10
20 83
50
11
21
[1]
[2] [3]
[5] [6]
[1]
[2] [3]
[4]
[1]
[2]
[4]
Max Heap
Min Heap
Example of Insertion to Max Heap
20
15 2
14 10
initial location of new node
21
15 20
14 10 2
insert 21 into heap
20
15 5
14 10 2
insert 5 into heap
Insertion into a Max Heap
void insert_max_heap(element item, int *n)
{
int i;
if (HEAP_FULL(*n)) {
fprintf(stderr, “the heap is full.n”);
exit(1);
}
i = ++(*n);
while ((i!=1)&&(item.key>heap[i/2].key)) {
heap[i] = heap[i/2];
i /= 2;
}
heap[i]= item;
}
2k-1=n ==> k=log2(n+1)
O(log2n)
Example of Deletion from Max Heap
20
remove
15 2
14 10
10
15 2
14
15
14 2
10
Deletion from a Max Heap
element delete_max_heap(int *n)
{
int parent, child;
element item, temp;
if (HEAP_EMPTY(*n)) {
fprintf(stderr, “The heap is emptyn”);
exit(1);
}
/* save value of the element with the
highest key */
item = heap[1];
/* use last element in heap to adjust heap */
temp = heap[(*n)--];
parent = 1;
child = 2;
while (child <= *n) {
/* find the larger child of the current
parent */
if ((child < *n)&&
(heap[child].key<heap[child+1].key))
child++;
if (temp.key >= heap[child].key) break;
/* move to the next lower level */
heap[parent] = heap[child];
child *= 2;
}
heap[parent] = temp;
return item;
}
Trees, Binary Search Tree, AVL Tree in Data Structures

Trees, Binary Search Tree, AVL Tree in Data Structures

  • 1.
    SUYASH BHARDWAJ FACULTY OFENGINEERING AND TECHNOLOGY GURUKUL KANGRI VISHWAVIDYALAYA, HARIDWAR
  • 2.
  • 3.
  • 4.
    Binary Tree Representation Array representation.  Linked representation.
  • 5.
    Array Representation  Numberthe nodes using the numbering scheme for a full binary tree. The node that is numbered i is stored in tree[i]. tree[] 0 5 10 a b c d e f g h i j b a c d e f g h i j 1 2 3 4 5 6 7 8 9 10
  • 6.
    Right-Skewed Binary Tree An n node binary tree needs an array whose length is between n+1 and 2n. a b 1 3 c 7 d 15 tree[] 0 5 10 a - b - - - c - - - - - - - 15 d
  • 7.
    Linked Representation  Eachbinary tree node is represented as an object whose data type is BinaryTreeNode.  The space required by an n node binary tree is n * (space required by one node).
  • 8.
    typedef struct node { intdata; struct node *lc,*rc; }; Link Representation of Binary Tree
  • 9.
  • 10.
    TREE  A treeis a hierarchical representation of a finite set of one or more data items such that: • There is a special node called the root of the tree. • The nodes other than the root node form an ordered pair of disjoint subtrees. Level 0 Level 1 Level 2 Root Leaf LeafLeaf
  • 11.
  • 12.
    Binary Tree Binary Treeis a rooted tree in which root can have maximum two children such that each of them is again a binary tree. That means, there can be 0,1, or 2 children of any node.
  • 13.
  • 14.
    Strict Binary Tree StrictBinary Tree is a Binary tree in which root can have exactly two children or no children at all. That means, there can be 0 or 2 children of any node.
  • 15.
  • 16.
    Complete Binary Tree CompleteBinary Tree is a Strict Binary tree in which every leaf node is at same level. That means, there are equal number of children in right and left subtree for every node.
  • 17.
    Extended Binary Tree A binary tree with special nodes replacing every null subtree. Every regular node has two children, and every special node has no children.
  • 18.
    Extended Binary Tree An extended binary tree is a transformation of any binary tree into a complete binary tree.  This transformation consists of replacing every null subtree of the original tree with “special nodes.”  The nodes from the original tree are then called as internal nodes, while the “special nodes” are called as external nodes.
  • 19.
    Tree Traversal :Pre order  Pre order (N L R)
  • 20.
    Tree Traversal :Pre order  Pre order (N L R) A
  • 21.
    Tree Traversal :Pre order  Pre order (N L R) A, B
  • 22.
    Tree Traversal :Pre order  Pre order (N L R) A, B, D
  • 23.
    Tree Traversal :Pre order  Pre order (N L R) A, B, D, E
  • 24.
    Tree Traversal :Pre order  Pre order (N L R) A, B, D, E, C
  • 25.
    Tree Traversal :Pre order  Pre order (N L R) A, B, D, E, C, F
  • 26.
    Tree Traversal :Pre order  Pre order (N L R) A, B, D, E, C, F, G
  • 27.
    Tree Traversal :In order  In order (L N R)
  • 28.
    Tree Traversal :In order  In order (L N R) D
  • 29.
    Tree Traversal :In order  In order (L N R) D, B
  • 30.
    Tree Traversal :In order  In order (L N R) D, B, E
  • 31.
    Tree Traversal :In order  In order (L N R) D, B, E, A
  • 32.
    Tree Traversal :In order  In order (L N R) D, B, E, A, F
  • 33.
    Tree Traversal :In order  In order (L N R) D, B, E, A, F, C
  • 34.
    Tree Traversal :In order  In order (L N R) D, B, E, A, F, C, G
  • 35.
    Tree Traversal :Post order  Post order (L R N)
  • 36.
    Tree Traversal :Post order  Post order (L R N) D
  • 37.
    Tree Traversal :Post order  Post order (L R N) D, E
  • 38.
    Tree Traversal :Post order  Post order (L R N) D, E, B
  • 39.
    Tree Traversal :Post order  Post order (L R N) D, E, B, F
  • 40.
    Tree Traversal :Post order  Post order (L R N) D, E, B, F, G
  • 41.
    Tree Traversal :Post order  Post order (L R N) D, E, B, F, G, C
  • 42.
    Tree Traversal :Post order  Post order (L R N) D, E, B, F, G, C, A
  • 43.
    Constructing Binary Tree In order – D, G, B, H, E, A, F, I, C  Pre order – A, B, D, G, E, H, C, F, I  Step 1 : finding the root  Root Node – A (from pre order)  Step 2 : Find left and right part of the root  Left part -  Right part -
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 58.
    Binary Search Tree Thevalue at any node, • Greater than every value in left subtree • Smaller than every value in right subtree – Example • Y > X • Y < Z Y X Z
  • 59.
    Binary Search Tree •Values in left sub tree less than parent • Values in right sub tree greater than parent • Fast searches in a Binary Search tree, maximum of log n comparisons 31 21 40 10 22 35 42
  • 60.
    • Examples Binary search trees Nota binary search tree 5 10 30 2 25 45 5 10 45 2 25 30 5 10 30 2 25 45 Binary Search Trees
  • 61.
    • search (root,25 ) 5 10 30 2 25 45 5 10 30 2 25 45 10 < 25, right 30 > 25, left 25 = 25, found 5 < 25, right 45 > 25, left 30 > 25, left 10 < 25, right 25 = 25, found Example Binary Searches
  • 62.
    Algorithm for BinarySearch Tree  A) compare ITEM with the root node N of the tree  i) if ITEM<N, proceed to the left child of N.  ii) if ITEM>N, proceed to the right child of N.  B) repeat step (A) until one of the following occurs  i) we meet a node N such that ITEM=N, i.e. search is successful.  ii) we meet an empty sub tree, i.e. the search is unsuccessful.
  • 63.
    typedef struct node { intdata; struct node *lc,*rc; }; Binary Tree Implementation
  • 64.
    search() { while (n !=NULL) { if (n->data == item) // Found it return n; if (n->data > item) // In left subtree n = n->lc; else // In right subtree n = n->rc; } return null; } Iterative Search of Binary Search Tree
  • 65.
    Search(node *n, info) { if(n == NULL) // Not found return( n ); else if (n->data == item) // Found it return( n ); else if (n->data > item) // In left subtree return search( n->left, item ); else // In right subtree return search( n->right, item ); } Recursive Search of Binary Search Tree
  • 66.
    Insertion in aBinary Search Tree • Algorithm 1. Perform search for value X 2. Search will end at node Y (if X not in tree) 3. If X < Y, insert new leaf X as new left subtree for Y 4. If X > Y, insert new leaf X as new right subtree for Y
  • 67.
    • Insert (20 ) 5 10 30 2 25 45 10 < 20, right 30 > 20, left 25 > 20, left Insert 20 on left 20 Insertion in a Binary Search Tree
  • 68.
    40 Insertion in aBinary Tree 40, 60, 50, 33, 55, 11
  • 69.
    40 Insertion in aBinary Tree 40, 60, 50, 33, 55, 11 60
  • 70.
    40 Insertion in aBinary Tree 40, 60, 50, 33, 55, 11 60 50
  • 71.
    40 Insertion in aBinary Tree 40, 60, 50, 33, 55, 11 60 50 33
  • 72.
    40 Insertion in aBinary Tree 40, 60, 50, 33, 55, 11 60 50 33 55
  • 73.
    40 Insertion in aBinary Tree 40, 60, 50, 33, 55, 11 60 50 33 55 11
  • 74.
    Deletion in BinaryTree • Algorithm 1. Perform search for value X 2. If X is a leaf, delete X 3. Else //we must delete internal node a) Replace with largest value Y on left subtree OR smallest value Z on right subtree b) Delete replacement value (Y or Z) from subtree Note :- – Deletions may unbalance tree
  • 75.
    Example Deletion (Leaf) •Delete ( 25 ) 5 10 30 2 25 45 10 < 25, right 30 > 25, left 25 = 25, delete 5 10 30 2 45
  • 76.
    Example Deletion (InternalNode) • Delete ( 10 ) 5 10 30 2 25 45 5 5 30 2 25 45 2 5 30 2 25 45 Replacing 10 with largest value in left subtree Replacing 5 with largest value in left subtree Deleting leaf
  • 77.
    Example Deletion (InternalNode) • Delete ( 10 ) 5 10 30 2 25 45 5 25 30 2 25 45 5 25 30 2 45 Replacing 10 with smallest value in right subtree Deleting leaf Resulting tree
  • 78.
    Binary Search Properties •Time of search – Proportional to height of tree – Balanced binary tree • O( log(n) ) time – Degenerate tree • O( n ) time • Like searching linked list / unsorted array
  • 79.
    AVL Tree  AVLtrees are height-balanced binary search trees  Balance factor of a node= height(left sub tree) - height(right sub tree)  An AVL tree has balance factor calculated at every node  For every node, heights of left and right sub tree can differ by no more than 1  Store current heights in each node
  • 80.
    AVL Tree  Abinary tree in which the difference of height of the right and left subtree of any node is less than or equal to 1 is known as AVL Tree.  Height of left subtree – height of right subtree can be either -1,0,1
  • 81.
  • 82.
    AVL Tree 1 0-1 0 10 0 0 Balanced as LST-RST=1 3 2
  • 83.
    Insertion in AVLTree Case 1: the node was either left heavy or right heavy and has become balanced
  • 84.
    Insertion in AVLTree Case 2: the node was balanced and has now become left or right heavy
  • 85.
    Insertion in AVLTree Case 3: the node was heavy and the new node has been inserted in the heavy sub tree thus creating an unbalanced sub tree 3 2
  • 86.
    Rebalancing • When thetree structure changes (e.g., insertion or deletion), we need to transform the tree to restore the AVL tree property. • This is done using single rotations or double rotations.
  • 87.
    Rotations • single rotations x y A B C y x A BC Before Rotation After Rotation e.g. Single Rotation
  • 88.
    • Since aninsertion/deletion involves adding/deleting a single node, this can only increase/decrease the height of some subtree by 1 • Thus, if the AVL tree property is violated at a node x, it means that the heights of left(x) and right(x) differ by exactly 2. • Rotations will be applied to x to restore the AVL tree property. Rotations
  • 89.
    The new itemis inserted in the subtree A. The AVL-property is violated at x height of left(x) is h+2 height of right(x) is h. Single Rotation
  • 90.
    Single rotation takesO(1) time. Insertion takes O(log N) time. The new item is inserted in the subtree C. The AVL-property is violated at x. Single Rotation
  • 91.
    The new keyis inserted in the subtree B1 or B2. The AVL-property is violated at x. x-y-z forms a zig-zag shape also called left-right rotate Double Rotation
  • 92.
    The new keyis inserted in the subtree B1 or B2. The AVL-property is violated at x. also called right-left rotate Double Rotation
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
    j k X Y Z Consider avalid AVL subtree AVL Insertion: Outside Case h h h
  • 109.
    j k X Y Z Inserting into X destroysthe AVL property at node j AVL Insertion: Outside Case h h+1 h
  • 110.
    j k X Y Z Do a “rightrotation” AVL Insertion: Outside Case h h+1 h
  • 111.
    j k X Y Z Do a “rightrotation” Single right rotation h h+1 h
  • 112.
    j k X Y Z “Rightrotation” done! (“Left rotation” is mirror symmetric) Outside Case Completed AVL property has been restored! h h+1 h
  • 113.
    j k X Y Z AVL Insertion:Inside Case Consider a valid AVL subtree h hh
  • 114.
    Inserting into Y destroysthe AVL property at node j j k X Y Z AVL Insertion: Inside Case Does “right rotation” restore balance? h h+1h
  • 115.
    j k X Y Z “Right rotation” does notrestore balance… now k is out of balance AVL Insertion: Inside Case h h+1 h
  • 116.
    Consider the structure ofsubtree Y… j k X Y Z AVL Insertion: Inside Case h h+1h
  • 117.
    j k X V Z W i Y = nodei and subtrees V and W AVL Insertion: Inside Case h h+1h h or h-1
  • 118.
    j k X V Z W i AVL Insertion: InsideCase We will do a left-right “double rotation” . . .
  • 119.
    j k X V Z W i Double rotation: first rotation left rotation complete
  • 120.
    j k X V Z W i Double rotation: second rotation Now do a right rotation
  • 121.
    jk X V ZW i Doublerotation : second rotation right rotation complete Balance has been restored hh h or h-1
  • 122.
    B-Tree All leaves areon the bottom level. All internal nodes (except perhaps the root node) have at least cell(m / 2) (nonempty) children. The root node can have as few as 2 children if it is an internal node, and can obviously have no children if the root node is a leaf (that is, the whole tree consists only of the root node). Each leaf node (other than the root node if it is a leaf) must contain at least ceil(m / 2) - 1 keys. B-tree is a fairly well-balanced tree.
  • 123.
    Let's work ourway through an example similar to that given by Kruse. Insert the following letters into what is originally an empty B-tree of order 5: C N G A H E K Q M F W L T Z D P R X Y S Order 5 means that a node can have a maximum of 5 children and 4 keys. All nodes other than the root must have a minimum of 2 keys. The first 4 letters get inserted into the same node, resulting in this picture:
  • 124.
    When we tryto insert the H, we find no room in this node, so we split it into 2 nodes, moving the median item G up into a new root node. Note that in practice we just leave the A and C in the current node and place the H and N into a new node to the right of the old one. Inserting E, K, and Q proceeds without requiring any splits: H E K Q M F W L T Z D P R X Y S
  • 125.
    Inserting M requiresa split. Note that M happens to be the median key and so is moved up into the parent node. The letters F, W, L, and T are then added without needing any split. M F W L T Z D P R X Y S
  • 126.
    When Z isadded, the rightmost leaf must be split. The median item T is moved up into the parent node. Note that by moving up the median key, the tree is kept fairly balanced, with 2 keys in each of the resulting nodes. The insertion of D causes the leftmost leaf to be split. D happens to be the median key and so is the one moved up into the parent node. The letters P, R, X, and Y are then added without any need of splitting: Z D P R X Y S
  • 127.
    Finally, when Sis added, the node with N, P, Q, and R splits, sending the median Q up to the parent. However, the parent node is full, so it splits, sending the median M up to form a new root node. Note how the 3 pointers from the old parent node stay in the revised node that contains D and G.
  • 128.
    HEAP A max treeis a tree in which the key value in each node is no smaller than the key values in its children. A max heap is a complete binary tree that is also a max tree. A min tree is a tree in which the key value in each node is no larger than the key values in its children. A min heap is a complete binary tree that is also a min tree. Operations on heaps: - creation of an empty heap - insertion of a new element into the heap; - deletion of the largest element from the heap
  • 129.
    14 12 7 810 6 9 63 5 30 25 [1] [2] [3] [5] [6] [1] [2] [3] [4] [1] [2] 2 7 4 810 6 10 20 83 50 11 21 [1] [2] [3] [5] [6] [1] [2] [3] [4] [1] [2] [4] Max Heap Min Heap
  • 130.
    Example of Insertionto Max Heap 20 15 2 14 10 initial location of new node 21 15 20 14 10 2 insert 21 into heap 20 15 5 14 10 2 insert 5 into heap
  • 131.
    Insertion into aMax Heap void insert_max_heap(element item, int *n) { int i; if (HEAP_FULL(*n)) { fprintf(stderr, “the heap is full.n”); exit(1); } i = ++(*n); while ((i!=1)&&(item.key>heap[i/2].key)) { heap[i] = heap[i/2]; i /= 2; } heap[i]= item; } 2k-1=n ==> k=log2(n+1) O(log2n)
  • 132.
    Example of Deletionfrom Max Heap 20 remove 15 2 14 10 10 15 2 14 15 14 2 10
  • 133.
    Deletion from aMax Heap element delete_max_heap(int *n) { int parent, child; element item, temp; if (HEAP_EMPTY(*n)) { fprintf(stderr, “The heap is emptyn”); exit(1); } /* save value of the element with the highest key */ item = heap[1]; /* use last element in heap to adjust heap */ temp = heap[(*n)--]; parent = 1; child = 2;
  • 134.
    while (child <=*n) { /* find the larger child of the current parent */ if ((child < *n)&& (heap[child].key<heap[child+1].key)) child++; if (temp.key >= heap[child].key) break; /* move to the next lower level */ heap[parent] = heap[child]; child *= 2; } heap[parent] = temp; return item; }