Vous êtes sur la page 1sur 74

# SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED

TREES

DATA STRUCTURES
III SEM CSE STUDENTS

## UNIT-II TREE STRUCTURES

&
UNIT-III BALANCED TREES

PREPARED BY:

M.PREMALATHA, LECT/CSE

HOD PRINCIPAL

## SENGUNTHAR ENGINEERINGCOLLEGE, TIRUCHENGODE

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
1
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

UNIT -II

TREE STRUCTURES

 Tree Traversals
 Left child right sibling data structures for general trees
 Binary Tree ADT
 Expression Trees
 Application of Trees
 Binary Search tree ADT
 Threaded Binary Trees

UNIT -III

BALANCED TREES

 AVL Trees
 Splay Trees
 B-tree
 Heaps
 Binary Heaps
 Application of binary heaps.

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
2
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
3
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

CONTENTS
S.NO 2 MARKS PAGE.NO
1 Define Tree. 5
Define Non-linear data structure. (OR)
2 Give two examples of non-linear data structures which are widely 5
used.(Apr/May2004)
3 What is meant by Binary tree? (Apr/May2004) 5
What are the various operations performed on binary tree using
4 linked representation? 6
5 What are the two methods of binary tree implementation? 6
What are the different types of tree traversal technique?
6 6
(Apr/May2004)
7 Define Pre-order traversal. 6
8 Define Post- order traversal. 6
9 Define In-order traversal. 7
10 Define Complete binary tree. 7
11 Define Full binary tree. 7
12 Define degree of a node and degree of a tree. 8
13 Define Terminal Node & Non-Terminal Node. 8
14 Define Binary Search tree. 8
15 What are the applications of trees? 9
16 List out the different types of Binary Trees. 9
17 What are the advantages of array representation of binary trees? 9
What are the disadvantages of array representation of binary
18 9
trees?
What are the advantages of Linked list representation of binary
19 9
trees?
What are the disadvantages of Linked list representation of binary
20 10
trees?
21 Define Strict binary trees: 10
22 What are Skewed binary trees? 10
23 What is threaded binary trees? 10
24 A binary tree with 20 nodes has null branches? 11
25 How many different trees are possible with 10 nodes? 11
Traverse the given tree using In order, Preorder and Post order
26 12
traversals.
There are 8, 15, 13, 14 nodes were there in 4 different trees. Which
27 12
of them could have formed a full binary tree?
In the given binary tree, using array you can store the node 4 at
28 13
which location?
29 Give the node structure for threaded binary tree. 13
30 What is an Expression tree? 14
31 What is the time complexity of binary search tree? 14
32 What is the significance of threaded binary tree? 14
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
4
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
5
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

## S.NO 2 MARKS PAGE.NO

33 What is meant by height balanced trees or AVL trees?
34 What is a balance factor in AVL trees?
35 Define AVL rotation.
What are the four-different cases of pointer manipulations done in
36 AVL rotation?
37 What is priority queue?
38 Application of priority queues?
39 What are the main properties of a binary heap?
40 Define lazy deletion?
41 Define AVL tree?
42 What are the various transformation performed in AVL tree?
43 Define max heap?
44 Define min heap?
45 What is the minimum number of nodes in an AVL tree of height 5?
46 What is the use of sentinel value in binary heap?
47 Define Splay trees.
48 What is meant by Splay rotations?
49 Give the different Classification splay rotation.
50 What is maxheap?
51 What are the two stages for heap sort?
52 In an AVL tree, at what condition the balancing is to be done?
What is the bucket size, when the overlapping and collision occur
53 at same time?
In RDBMS, what is the efficient data structure used in the internal
54 storage representation?
Draw the B-tree of order 3 created by inserting the following data
55 arriving in sequence – 92 24 6 7 11 8 22 4 5 16 19 20 78
56 Define B-trees.
57 What are the different Splay Operations ?
58 What are the advantages of B-Trees?
59 List the application of B-Trees?
60 What is the height of B-Trees?

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
6
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

CONTENTS
S.NO 16 MARKS / 6 QUESTIONS PAGE.NO
a)Explain how to convert general tree into Binary tree. (Apr/May2004) (OR)
1 15
b).Write an algorithm to convert general tree into Binary tree.
a)Explain Binary Tree Traversal in C. (OR)
b) Give and explain the various tree traversal algorithms with example.
2 (Nov/Dec 2003). 20
c) What are the different tree traversals? Explain with examples. (Nov/Dec
2005)
a)What are the different ways of Binary Tree representations? (OR)
3 b)How is a binary tree represented using an array? Give example.(apr/nov 23
05)
a).What is the use of Find-min and Find-max procedures? Explain the Find
4 operation for binary search trees with example.(OR) 28
b)Write algorithm to locate an element from binary search tree. (Nov/Dec05)
5 30
Explain in detail about threaded binary tree with example.
Explain in detail about application of binary tree.
(OR)
6 Construct an expression tree for the given expression 34
i)2 + 3 * ( 4 – 6 / 2 + 7 ) / (2 + 3) – (4 –1) * (2 – 10 / 2))
ii)a - b( c * d / a + a) * b + a

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
7
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

2MARKS Q&A

1. Define Tree
A tree is a data structure, which represents hierarchical relationship
between individual data item.
A tree is a finite set of one or more nodes such that
 There is a specially designated node called root.
 The remaining nodes are partitioned into n>= 0 disjoint
sets a, b, c, d…. n
Where a, b, c, d are called the sub trees of the root
A tree is shown in the following fig.

L R
S

a b c d

## 2. Define Non-linear data structure. (OR)

Give two examples of non-linear data structures, which are widely used.
(Apr/May2004)
Data structure, which is capable of expressing more complex relationship
than that of physical adjacent, is called non-linear data structure.
Example: Trees, graph.

## 3. What is meant by Binary tree? (Apr/May2004)

A binary tree is a finite set of nodes which is either empty or consists of a root
and two disjoint binary trees called the left sub-tree and right sub-tree.(OR)In an
m-ary tree, if m=2, then it is a binary tre Each node has not more than 2 child
nodes, each of which may be a Leaf node.
Application:
Binary tree is used in
 data processing.
 File index schemes
 Hierarchical database management systems.

4. What are the various operations performed on binary tree using linked
representation?
The operations of binary tree that use linked list representation are,
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
8
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

##  Insertion – Insert a given item into a tree.

 Traversal – Processing the nodes of the tree one by one.
 Search – Search for the specified item.
 Copying – To obtain the exact copy of the given tree.
 Deletion – Delete an item from the tree.

## 5. What are the two methods of binary tree implementation?

Two methods to implement binary tree are,
 Linear representation.

## 6. What are the different types of tree traversal technique? (Apr/May2004)

The different types of tree traversal technique are,
 Pre-order traversal – yields prefix form of expression.
 In-order traversal - yields Infix form of expression.
 Post- order traversal - yields Postfix form of expression.

## 7. Define Pre-order traversal.

Pre-order traversal entains the following steps:
 Process the root node.
 Process the left sub tree.
 Process the right sub tree.
E.g.
+

O/P: +AB
A B

## 8. Define Post- order traversal.

Post- order traversal entains the following steps:
 Process the left sub tree.
 Process the right sub tree.
 Process the root node.
E.g.
+
O/P: AB+

A B

## 9. Define In-order traversal.

In-order traversal entains the following steps:
 Process the left sub tree.
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
9
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

##  Process the root node.

 Process the right sub tree.

E.g.
+
O/P: A+B

A B

## 10. Define complete binary tree.

A binary tree is said to be a complete binary tree, if all its level, except
possibly the last level, have the maximum number of possible nodes, all the
nodes at the last level appear as far left as possible.

L R
S

A B C

## A binary tree is a full binary tree, if it contains maximum possible number of

nodes in all level.

L R
S

A B C D

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
10
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

## 12. Define degree of a node and degree of a tree.

Degree of a Node:
The degree of node is the number of sub trees of a node in a given tree. The tree
given in figure.1, degree of each node as

C
B

D E

Figure:1
Degree (A)=2
Degree (B)=2
Degree (C)=0
Degree (D)=0

Degree of a Tree:
The degree of a tree is the maximum degree of any node in that tree.

## 13. Define Terminal Node & Non-Terminal Node.

Terminal Node: A node with degree zero is called a terminal node or a Leaf. In
the above tree, there are three terminal nodes or leaves such as C, D, and E.
Non-Terminal Node: Any node whose degree is not zero is called non-terminal
node. In the above tree, there are two non terminal nodes such as A, B.

## 14. Define Binary Search tree.

A Binary Search tree ‘t’ is a binary tree; either it is empty or each node in
the tree contains an identifier and
 All identifier in the left sub tree of ‘t’ are less (numerically or
alphanumerically) than the identifier in the root Node +.
 All identifier in the right sub tree of ‘t’ are greater than the identifier in the
root Node +.
 The left and right sub trees of ‘t’ are also binary search trees.

## 15. What are the applications of trees?

Applications of trees are,
 Trees are used in the representation of sets.
 Decision-making. E.g.: Eight coins problem.
 Computer-games such as chess, tic-tac-toe, checkers etc., are created
and executed using trees.
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
11
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

##  Manipulation of arithmetic expression.

 Symbol table construction.
 Syntax-analysis.

##  Strict binary trees

 Complete binary trees
 Full binary trees
 Skewed binary trees
 Heap trees.

## 17. What are the advantages of array representation of binary trees?

 The only advantages with this type of representation is that the direct
access to any node can be possible & finding the parent or left, right child
of any particular node is fast because of the random access.

##  The major disadvantage with this type of representation is wastages of

memory.
 In this type of representation the maximum depth of the tree has to be
fixed, because we have decide the array size.
 The insertion and deletion of any node in the tree will be costlier as other
nodes have to be adjusted at appropriate positions. So that the meaning
of binary tree can be preserved.

19. What are the advantages of Linked list representation of binary trees?

##  Using this array representation as there is no wastage of memory & so

there is no need to have prior knowledge of depth of the tree.
 Insertion & deletion, which are the most common operation, can be done
without moving the other nodes.

## 20. What are the disadvantages of Linked list representation of binary

trees?

 This representation does not provide direct access to a node and special
algorithms are required.
 This representation needs additional space in each node for storing the
left and right sub-trees.

## 21. Define Strict binary trees:

A strict binary tree is a binary tree in which every non-terminal node
consists of non-empty left sub tree and right sub tree.
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
12
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

B C
S

D E F G

D E

## 22. What are Skewed binary trees?

A binary tree with either left sub tree alone or right sub tree alone is
termed as Skewed binary tree. If there is only left subtree, it is said to be left
skewed tree. If there is only right sub tree, it is said to be right skewed tree.

## 23. What is threaded binary trees?

A binary tree in which every node that does not have a right child has a
THREAD to its INORDER successor is known as threaded binary tree.

## 24. A binary tree with 20 nodes has null branches?

21
Let us take a tree with 5 nodes (n=5)

## It will have only 6 (ie,5+1) null branches. In general,

A binary tree with n nodes has exactly n+ 1 null node.

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
13
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

## 25. How many different trees are possible with 10 nodes?

1014
For example, consider a tree with 3 nodes(n=3), it will have the maximum
combination of 5 different (ie,23 - 3 = 5) trees.

In general:
If there are n nodes, there exist 2n -n different trees.

26. Traverse the given tree using In order, Preorder and Post order
traversals.

 In order : D H B E A F C I G J
 Pre order : A B D H E C F G I J
 Post order : H D E B F I J G C A

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
14
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

27. There are 8, 15, 13, 14 nodes were there in 4 different trees. Which of
them could have formed a full binary tree?
15.
In general:
There are 2n-1 nodes in a full binary tree.

## By the method of elimination:

Full binary trees contain odd number of nodes. So there cannot be full
binary trees with 8 or 14 nodes, so rejected. With 13 nodes you can form a
complete binary tree but not a full binary tree. So the correct answer is 15.

Note:
Full and Complete binary trees are different. All full binary trees are
complete binary trees but not vice versa.

28. In the given binary tree, using array you can store the node 4 at which
location?

## 29. Give the node structure for threaded binary tree.

A Threaded Binary Tree is a binary tree in which every node that does not
have a right child has a THREAD (in actual sense, a link) to its INORDER
successor. By doing this threading we avoid the recursive method of traversing a
Tree, which makes use of stacks and consumes a lot of memory and time.
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
15
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

The node structure for a threaded binary tree varies a bit and its like this --
struct NODE
{
struct NODE *leftchild;
int node_value;
struct NODE *rightchild;
}

## 30. What is an Expression tree?

An Expression tree is a tree which is build from infix or prefix or postfix
expression. Generally in such tree parent node or root node is an operator where as the
children are operands.

## 31.What is the time complexity of binary search tree?

The complexity of binary search tree is n log2 n.

## 32. What is the significance of threaded binary tree?

In threaded binary tree the NULL pointers are replaced by some addresses. The
left pointer of the node points to its predecessor and the right pointer of the node points
to its successor. Because of this arrangement of pointers accessing predecessor or
successor of any node very efficient.

## 33. What is meant by height balanced trees or AVL trees?

A tree is said to be height balanced if all its nodes have a balance factor of
1, 0 or –1.Height balancing, attempts to maintain trees that posses the
ordering property in a form close to fullness. AVL – Adulation VelsKii and Landis.

## 34. What is a balance factor in AVL trees?

Balance factor of a node is defined to be the difference between the heights
of the node’s left sub tree and the height of the node’s right sub tree.

## 35. Define AVL rotation.

Manipulation of tree pointers is centered at the pivot node to bring the tree
into height balance. The visual effect of this pointer manipulation is to ‘rotate’ the
sub tree whose root is the pivot node. This operation is referred as AVL rotation.

## 36. What are the four-different cases of pointer manipulations done in

AVL rotation?
The four-different cases of pointer manipulations are,
 Insertion occurred in the left sub tree of the left child of the pivot node.
 Insertion occurred in the right sub tree of the right child of the pivot
node.
 Insertion occurred in the right sub tree of the left child of the pivot node.
 Insertion occurred in the left sub tree of the right child of the pivot node.

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
16
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

## 37. What is priority queue?

A priority queue is a data structure that allows at least the following two
operations: insert which does the obvious thing; and Deletemin, which finds,
returns, and removes the minimum element in the priority queue. The Insert
operation is the equivalent of Enqueue

## 38. Application of priority queues?

1. for scheduling purpose in operating system
2. used for external sorting
3. important for the implementation of greedy algorithm, which operates
by repeatedly finding a minimum.

## 39. What are the main properties of a binary heap?

1. Structure property
2. Heaporder property

## 40. Define lazy deletion?

When an element is to be deleted it is left in the tree itself and
marked a s being deleted. This is called as lazy deletion and is an efficient
procedure if duplicate keys are present in the binary search tree, because
the field that keeps count of the frequency of appearance of the element
can be decremented of the element can be decremented.

## 41. Define AVL tree?

AVL tree also called as height balanced tree .It is a height
balanced tree in which every node will have a balancing factor of –1,0,1
Balancing factor
Balancing factor of a node is given by the difference between the
height of the left sub tree and the height of the right sub tree.

## 42. What are the various transformation performed in AVL tree?

1. Single rotation
 Single L rotation
 Single R rotation
2.double rotation
 LR rotation
 RL rotation

## 43. Define max heap?

A heap in which the parent has a larger key than the child's is called a
max heap.

## 44. Define min heap?

A heap in which the parent has a smaller key than the child is called a min
heap.
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
17
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

## 45. What is the minimum number of nodes in an AVL tree of height 5?

If h is the height of an AVL tree then minimum number of nodes can be
obtained for such AVL tree using the formula
N(h)=1+N(h-1)+N(h-2)
N(5)=20.

## 46. What is the use of sentinel value in binary heap?

In binary heap sentinel value is used to indicate end of data or end of
process. Typically min heap has a root node which stores sentinel value. This
value is useful to terminate the loop when we traverse the binary heap
completely.

## 47. Define Splay trees.

Splay trees are binary search trees with a self adjusting mechanism (i.e.,)
A frequently accessed nodes are moved towards the root, which makes the
further retrievals of the same node to be efficient.
A splay tree is a binary search tree where a node is splayed after it is
accessed (for a search or update) Deepest internal node accessed is splayed.
Splaying costs O(h), where h is height of the tree which is still O(n) worst- case
O(h) rotations, each of which is O(1)

## 48. What is meant by Splay rotations?

Pushing the node towards the root is known as splay rotations. To move
the accessed node up by two levels, we need to keep track the path from the root
to the accessed node. Whenever the path turns left, it is named as Zig and if it
turns right, it is named as Zag.

## 49. Give the different Classification splay rotation.

The path could be either a single step or two steps
Single step rotations
 Zig
 Zag
Double Rotations
 Zig-Zig
 Zig-Zag
 Zag-Zig
 Zag-Zag

## 50. What is maxheap?

If we want the elements in the more typical increasing sorted
order,we can change the ordering property so that the parent has a
larger key than the child.it is called max heap.
51. What are the two stages for heap sort?
Stage 1 : Construction of heap
Stage 2 : Root deletion N-1 times
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
18
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

## 52. In an AVL tree, at what condition the balancing is to be done?

If the ‘pivotal value’ (or the ‘Height factor’) is greater than 1 or less
than –1.

53. What is the bucket size, when the overlapping and collision occur at
same time?
One. If there is only one entry possible in the bucket, when the collision
occurs, there is no way to accommodate the colliding value. This results in the
overlapping of values.

54. In RDBMS, what is the efficient data structure used in the internal
storage representation?

B+ tree. Because in B+ tree, all the data is stored only in leaf nodes, that
makes searching easier. This corresponds to the records that shall be stored in
leaf nodes.

55. Draw the B-tree of order 3 created by inserting the following data
arriving in sequence – 92 24 6 7 11 8 22 4 5 16 19 20 78

## 56. Define B-trees.

B-trees are balanced trees that are optimized for situations when part or
all of the tree must be maintained in secondary storage such as a magnetic disk.
Since disk accesses are expensive (time consuming) operations, a b-tree tries to
minimize the number of disk accesses.

## 57. What are the different Splay Operations ?

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
19
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

Access (i, t): if i is in tree t return pointer to i, otherwise return null pointer
Find i, then splay tree t at i. If i is not in tree t, then splay last node
accessed looking for i
Join (a, b): Return tree formed by combining tree "a", and tree "b". Assumes that
every item in "a" has key less then every item in "b"
Splay largest item in "a", then add "b" as a right child of root of "a"
Split (i, t): Split tree t, containing item i, into two trees: "a", containing all items
with key less or equal to "i"; and "b", containing all items with key greater than "i"
Perform access(i, t) then split tree at root
Insert (i, t): insert i in tree t.
Perform split (i, t) then make i the root of the two trees returned by split
Delete (i, t): delete i from tree t
Perform access(i, t) then perform join on t's subtrees

## 58. What is the height of B-Trees?

For n greater than or equal to one, the height of an n-key b-tree T of height h with
a minimum degree t greater than or equal to 2,

## 59. List the application of B-Trees.

 Database implementation
 Indexing on non primary key fields is also possible

## 60. What are the advantages of B-Trees?

There are limitations on size of the collection that can be maintained in main
memory. When data is maintained in the disk, it is important to reduce the
number of disk access. Many search tree performs this task, by reducing the
number of levels.

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
20
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

16 MARKS Q&A

## 1)a)Explain how to convert general tree into Binary tree.

(Apr/May2004)(OR)
b) Write an algorithm to convert general tree into Binary tree.

## Conversion of general tree to Binary tree

Algorithm
1. Assign Head node.
LEVEL=0
2.Read level no, name from general tree
3.Create node structure for new i/p
DATA=NAME
4.Comparision b/w the previous level with current level
If (previous node level < current node level)
LLINK (previous node) = current node
Else
a) While (previous node level > current node level)
Move previous
End while
b) [Previous node level = current node level]
RLINK (previous node)= current node.
5.Repeat from step 2 for all i/p’s.
6.End

## E.g. {Use Right heavy general tree} Level no name

1) 1 A
A 2 B
2 C
3 D
B C 3 E
3 F

D E F

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
21
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

E.G.
G Level no name
2) 1 G
2 H
2 I
I J 2 J
H

## 2. New i/p, read level no, name 1,A

N A N
Previous node level =0
Current node level = 1
1>0
 Left link of previous to current node Head

N A N

## 3. Read level no, name 2,B

N B N
Previous node level =1
Current node level = 2
2>1
 Left link of previous to current node Head

A N

N B N

## 4. Read level no, name 2,C

N C N
Previous node level =2
Current node level = 2
2 =2

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
22
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

A N

N B N C N

## 5. Read level no, name 3,D

N D N
Previous node level =2
Current node level =3
3>2
 Left Link of previous to current node

A N

N B C N

N D N

N E N

## Previous node level =3

Current node level = 3
3 =3
 Right Link of previous to current node

A N

N B C N

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
23
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

N D E N

## 7. Read level no, name 3,F

N F N
Previous node level =3
Current node level =3
3=3
 Right Link of previous to current node

A N

N B C N

N D E F N

LEFT
8. Read level no, name 1,G
N G N
Previous node level =3
Current node level =1
3 >1 (find up to same level)
Move previous up to it reach level 1.
1=1
 Right Link of previous to current node

A N G

LEF
T
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
24
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

## 9. Read level no, name 2,H

N H N
Previous node level =1
Current node level =2
2>1
 Left Link of previous to current node

A G

LEFT N H N

## 10. Read level no, name 2,I

N I N
Previous node level =2
Current node level =2
2=2
 Right Link of previous to current node

A G

LEFT N H N I N

## 11. Read level no, name 2,J

N J N
Previous node level =2
Current node level =2
2>1

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
25
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

##  Right Link of previous to current node

A G

LEFT N H N I N J N

A G

N H N I N J N

N B C N

N D E F N

## 2) a)Explain Binary Tree Traversal in C. (OR)

b)Give and explain the various tree traversal algorithms with
example. (Nov/Dec 2003).
c)What are the different tree traversals? Explain with
examples. (Nov/Dec 2005)

Traversing the tree means visiting each node exactly once. Because there are six
ways to traverse a tree. For these tree traversals we will use some notations as follows:
1. L means move to the Left Child.
2. R means move to the Right Child.
3. D means the Root/Parent node.

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
26
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

Now, with this L, R, D one can have six different combinations of L, R, and D nodes.
Such as LDR, LRD, DLR, DRL, RLD, RDL. But from computing point of view we will
have three different ways to traversing a tree. These three combinations will be LDR,
LRD, and DLR. Those are called In order; Post order, Pre order traversal respectively.

In order traversal:

A Print 3rd

## Print 2nd B D Print 4th

Print 1st
C
E
Print this node
at last

In order traversals are tracing the sequence “LDR” this type of traversal is
called in order traversal. The basic principal is to traverse left sub-tree then root and then
the right sub-tree.

## C – B – A – D –E is the in order traversal (ie). 1 st we go towards the left most

node. (ie) ‘C’. So print that the node C. Then go back to the node B and print B. Then
root node A then move towards the right sub tree print D and finally E.

## Algorithm for In order traversal

INORDER (Root)
1. [Start from root]
ptr=root
2. [Check the ptr value]
If (ptr! =NULL) then
i) INORDER (Ptr. Lc) /*Traverse the left sub-tree
ii) VISIT (ptr) /* visit the node
iii) INORDER (Ptr. Rc) /* Traverse the right sub-tree
3. End if
4. Stop

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
27
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

## Pre order traversal:

Print 1st
A
Print 2nd Print 4th

B D

Print this
Print 3rd node at last
C E

## A – B – C –D – E is the preorder traversal of the above figure.

We are following “DLR” path (ie) data at the root node will be printed first, then we
move on the left sub-tree and go on printing the data at the node & then to the right sub-
tree. Follow the same DLR principal at each sub-tree & go on printing the data
accordingly.

## Algorithm for Pre order traversal

PREORDER (Root)
1. [Start from root]
ptr=root
2. [Check the ptr value]
If (ptr! =NULL) then
i) VISIT (ptr) /* visit the node
ii) PREORDER (Ptr. Lc) /*Traverse the left sub-tree
iii) PREORDER (Ptr. Rc) /* Traverse the right sub-tree
3. End if
4. Stop

## Print this node at last

A

Print 3rd
B E Print 4th

C
Print 1st D Print 2nd

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
28
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

## From the figure post order sequence is C – D – B – E – A.

In post order traversal we are following the “LRD” principle (ie) move to the left
most node check if right sub-tree is there or not then print the left most, if right sub-tree is
there move towards the right most node. The key idea here is that at each sub-tree we are
following the LRD principal and print the data according.

## Algorithm for Post order traversal

POSTORDER (Root)
1. [Start from root]
ptr=root
2. [Check the ptr value]
If (ptr! =NULL) then
i) POSTORDER (Ptr. Lc) /*Traverse the left sub-tree
ii) POSTORDER (Ptr. Rc) /* Traverse the right sub-tree
iii) VISIT (ptr) /* visit the node
3. End if
4. Stop

## 3)a)What are the different ways of Binary Tree representations?

(OR)
b) How is a binary tree represented using an array? Give example.
(Nov/Dec 05)

## There are two ways of represent ting the Binary Tree.

 Sequential Representation

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
29
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

Sequential Representation

Each node is sequentially arranged from top to bottom & front left to right. Let us
understand this matter by numbering each node. The numbering will start from root node
and then remaining nodes will give ever-increasing numbers in level wise direction. The
nodes on the same level will be numbered from left to right. The numbering will us
shown below in figure.
A

C
B

F G
D E

N O
H I J K L M

You will get a point that a binary tree of depth ‘n’ having 2n-1 number of nodes. In
the figure the tree is having the depth 4 and total number of nodes are 15.
Thus remember that is a binary tree of depth ‘n’ there will be a maximum 2n-1 nodes.
And so if we know the maximum depth of the tree than we can represent binary tree
using arrays data structure.
We can use array size of ‘n’. The root will be at position 1. Its left child will be at
position 2; its right child will be at position 3 and so on.
The way of placing the elements in the array is by applying the formula is as below.
Parent (n) = floor [(n-1)/2] where n>0 when n is equal to 0 the root node will be
placed at that location & root node is not having any parent.
Left (n) =(2n +1)
Right (n) = (2n+2)
Root = A =index 0
Left child of A i.e.; n =0

## B will be at 2*0+1=1st location

Similarly left right child of ‘A ‘ which will be C

## C will be at 2*0+2=2nd location

I is at the 8th location
2n + 2 =8
2n = 8 –2 =6
2n = 6
n = 6/2 = 3
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
30
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

## That means parent of I is at the 3rd location and i.e. P

B C

D E F G

H I

A 0

B 1

C 2

D 3

E 4

F 5

G 6

H 7

I
8

 The only advantages with this type of representation is that the direct access to
any node can be possible & finding the parent or left, right child of any particular
node is fast because of the random access.
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
31
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

##  The major disadvantage with this type of representation is wastages of memory.

 In this type of representation the maximum depth of the tree has to be fixed,
because we have decide the array size.
 The insertion and deletion of any node in the tree will be costlier as other nodes
have to be adjusted at appropriate positions. So that the meaning of binary tree
can be preserved.

## In linked list each node will be look like this

Left Right
child Data child

In binary tree each node will have left child, right child and data field.
The left child is nothing but the left link which points to some address of left sub
tree where as right child is also a right link which points to some address of right Sub
tree. And the data field gives the information about the node.
Let us see the ‘C’ structure of the node to a binary tree.

## Type def struct node

{
int data;
struct node *left;
struct node *right;
} bin;

B C

E
D

## Add of node B A Add of node C

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
Add of node B Add of node Null C Null 32
D E
Null E Null
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

Null D Null

 Using this array representation as there is no wastage of memory & so there is
no need to have prior knowledge of depth of the tree.
 Insertion & deletion, which are the most common operation, can be done
without moving the other nodes.

 This representation does not provide direct access to a node and special
algorithms are required.
 This representation needs additional space in each node for storing the left and
right sub-trees.

## 4)a)What is the use of Find-min and Find-max procedures?

Explain the Find operation for binary search trees with example.
(OR)
b) Write algorithm to locate an element from binary search
tree.(Nov/Dec05)

Find This operation generally requires returning a pointer to the node in tree T
that has key X or NULL if there is no such node. The public routine that returns nonzero
if the Find succeeded, and sets Last Find. If the find failed, zero is returned, and Last
Find point to NULL. The structure of the tree makes this simple. If T is NULL, then we
return 0. Otherwise, if the key stored at T is X, we can return T other wise, we make a
recursive call on a sub tree of T, either left or right, depending on the relationship of X to
the key stored in T.

## Find operation for binary search trees algorithm is given below:

Template < class Etype>
Tree_Node<Etype>*
Binary_Search_Tree<Etype>
Find (const Etype & X, Tree-Node<Etype>* T) const
{
If (T==NULL)
Return NULL;
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
33
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

Else
If (x<TElement)
Return Find (X, TLeft); /* Find the element at Left */
Else
If (x > TElement)
Return Find (X, TRight); /* Find the element at Right */
Else
Return T;
}

## Find_Min and Find_Max:

To perform a Find_Min, start at the root and go left, as there is a left child. The stopping
point is the smallest element. The Find_Max routine is the same; expect that branching be
to the right child. The public interface is similar to that of the Find routine.

## Template < class Etype>

Tree_Node<Etype>*
Binary_Search_Tree<Etype>
Find_Min (Tree Node < Etype>* T) const
{
If (T==NULL)
Return NULL;
Else
If (TLeft ==NULL)
Return T;
Else
Return Find_Min (TLeft);
}

This is so easy that many programmers do not bother using recursion. We will code the
routines both ways by doing Find_Min recursively and Find_Max non-recursively.
Notice how we carefully handle the degenerate case o an empty tree; although this is
always important to do, it is recursive programs.
Algorithm for Nonrecursive implementation of Find_Max for binary Search trees

## Template < class Etype>

Void
Binary_Search_Tree<Etype>
Find_Max (Tree_Node < Etype>* T) const
{
If (T! =NULL)
While (TRight! = NULL)
T = TRight;
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
34
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

Return T;
}
INSERT
To insert X into tree T, process down the tree as you would with a FIND
procedure. If X is found, do nothing; otherwise, insert X at last position on the path
traversed.

6 6

2 8 2 8

1 4 1 4

Insert 5
3 3 5
Algorithm to insert into a binary search tree

template<class type>
Void Binary_search_Tree<Etype>::
Insert (Const Etype &X, Tree-Node<Etype> * & T)
{
If (T==NULL)
{
T=new Tree_Node<Etype>(X);
If (T==NULL)
Error (“out of space”);
}
Else
If (X < T ->Element)
Insert (X, T->Left);
Else
If(X > T ->Element)
Insert (X, T->Right); }

## Threaded Binary Tree

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
35
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

A Threaded Binary Tree is a binary tree in which every node that does not have a
right child has a THREAD (in actual sense, a link) to its INORDER successor. By doing
this threading we avoid the recursive method of traversing a Tree, which makes use of
stacks and consumes a lot of memory and time.

The node structure for a threaded binary tree varies a bit and its like this --
struct NODE
{
struct NODE *leftchild;
int node_value;
struct NODE *rightchild;
}

Let's make the Threaded Binary tree out of a normal binary tree...

The INORDER traversal for the above tree is -- D B A E C. So, the respective Threaded
Binary tree will be --

B has no right child and its inorder successor is A and so a thread has been made in
between them. Similarly, for D and E. C has no right child but it has no inorder successor
even, so it has a hanging thread.

## As this is a non-recursive method for traversal, it has to be an iterative procedure;

meaning, all the steps for the traversal of a node have to be under a loop so that the same
can be applied to all the nodes in the tree.

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
36
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

I'll consider the INORDER traversal again. Here, for every node, we'll visit the
left sub-tree (if it exists) first (if and only if we haven't visited it earlier); then we visit (i.e
print its value, in our case) the node itself and then the right sub-tree (if it exists). If the
right sub-tree is not there, we check for the threaded link and make the threaded node the
current node in consideration. Please, follow the example given below.

List of visited
nodes: INORDER:
step-1:'A' has a left child i.e B, which has B
not been visited. So, we put B in our
"list of visited nodes" and B
becomes our current node in
consideration.
step-2:'B' also has a left child, 'D', which is BD
not there in our list of visited nodes.
So, we put 'D' in that list and make it
our current node in consideration.
step-3:'D' has no left child, so we print 'D'. BD D
Then we check for its right child. 'D'
has no right child and thus we check
going till node 'B'. So, we make 'B'
as our current node in consideration.
step-4:'B' certainly has a left child but its BD DB
already in our list of visited nodes.
So, we print 'B'. Then we check for
its right child but it doesn't exist. So,
we make its threaded node (i.e 'A')
as our current node in consideration.
step-5:'A' has a left child, 'B', but its BDC DBA
already there in the list of visited
nodes. So, we print 'A'. Then we
check for its right child. 'A' has a
right child, 'C' and its not there in
our list of visited nodes. So, we add
it to that list and we make it our
current node in consideration.
step-6:'C' has 'E' as the left child and its not BDCE DBA
there in our list of visited nodes
even. So, we add it to that list and
make it our current node in
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
37
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

consideration.
and finally..... DBEAC

Algorithm:-
Step-1: For the current node check whether it has a left child which is not there in the
visited list. If it has then go to step-2 or else step-3.
Step-2: Put that left child in the list of visited nodes and make it your current node in
consideration. Go to step-6.
Step-3: For the current node check whether it has a right child. If it has then go to step-4
else go to step-5
Step-4: Make that right child as your current node in consideration. Go to step-6.
Step-5: Check for the threaded node and if its there make it your current node.
Step-6: Go to step-1 if all the nodes are not over otherwise quit

C implementation:-
struct NODE
{
struct NODE *left;
int value;
struct NODE *right;
}

## inorder(struct NODE *curr)

{
while(all the nodes are not over )
{
if(curr->left != NULL && ! visited(curr->left))
{
visit(curr->left);
curr = curr->left;
}
else
{
printf("%d", curr->value);
if(curr->right != NULL)
curr = curr->right;
else
}
}
}

## 6. Explain in detail about application of binary tree.

(OR)
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
38
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

## Construct an expression tree for the given expression

i)2 + 3 * ( 4 – 6 / 2 + 7 ) / (2 + 3) – (4 –1) * (2 – 10 / 2))
ii)a - b( c * d / a + a) * b + a

Expression Trees:
We have already seen how to solve expressions in form of postfix or prefix form
with the help of stacks. Expressions can also be solved using tree called as
expression trees.
Consider an infix expression:

2 + 3 * ( 4 – 6 / 2 + 7 ) / (2 + 3) – (4 –1) * (2 – 10 / 2))
The expression tree for this expression is:

We can observe that an expression tree has the operators in all roots and the
operands are in leaves of the respective operators. The evaluations will always being
from the bottom of the tree, i.e. 6/2 is the first operation, which confirms with the usual
procedure shown above. A wrong expression tree, would result in wrong answer.

e.g.
4 – 2 - 3. The answer is –1. The expression trees could be

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
39
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

The difference in the trees is due to the associativity rules. In the first case, 2-3
will be evaluated first, resulting in –1 and then it will be subtracted from 4 resulting in 5.
In the second case, 4-2 will be evaluated first, resulting in 2 and after subtracting 3, we
get the answer as –1. Hence we can conclude that the second tree is proper.

When it comes to solving the expression, using computer, the expression in the
infix form would be slightly troublesome, or if we make certain conversions, the
evaluations will be much easier. These forms are, namely, prefix and postfix
expressions.

We will see another example by drawing the expression tree for the following expression
a - b( c * d / a + a) * b + a
The easiest way for evaluation as well as for the other purposes, is to write expression in
fully parenthesized form. During this process, we should consider the steps for
evaluation.
a–b-(c*d/a+a)*b+a
=a–b-(c*e+a)*b+a
1 = a – b - ( e+ a ) * b + a
2 = a – b – e3 * b + a
= a – b - e4 + a
= e6 + a
= e7

Forming the tree will be easy from any of the above notations. Travel from bottom
to root.

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
40
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
41
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
42
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

The other way of generating the tree is to convert the expression to the fully
parenthesized from. Then every time you remove the pair of brackets you will get two
operands separated by an operator, make that operator, the root and the two operands
as left and right child and repeat the process.

## Conversion to the fully parenthesized form is shown below:

a–b-(c*d/a+a)*b+a

=a–b-(c*(d/a+a)*b+a
=a–b-((c*(d/a+a))*b+a
= a –b - ( ( ( c * ( d / a ) ) + a ) * b + a
=(a–b)-(((c*(d/a))+a)*b)+a
= ( ( a – b ) - ( ( ( c * ( d / a ) ) + a) * b ) ) + a
=(((a–b)-(((c*(d/a))+a)*b))+a)

During evaluation we will have to solve the inner most bracket first as its priority
will be the highest. Writing e1, e2, e3, etc is equivalent to putting the brackets, which is
as shown below.

7.a) how do you insert an element into an AVL tree? (May/Jun 05)
(OR)
b) Write a function to generate the AVL tree of height H with
fewest nodes. (May/Jun 2005) (OR)
c) Explain the single rotation and double rotation in an AVL tree.
(OR)

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
43
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

## d) Write the routine to perform single rotation and double

rotation.
AVL TREES:
Invented by Russian scientists G.M.Adelson-velsky and E.M.Landis in 1962.
Definition:
An AVL tree is a binary tree in which the balance factor of every node is either 0
or 1, which is defined as difference between the heights of the nodes left &right sub
trees.
 Height is maintained more or less in balanced tree so maintaining another
factor called balancing factor.
 Height for each node is calculated by
 Height of left sub tree – Height of right sub tree.
 It may have values 0,1 for AVL tree.
 Height of tree differs almost by 1.
 If it becomes 2 then we have to adjust to become 1,the node having
balance factor as 2 is called pivot node, whose balance factor 2.
 If the node is more than one ( 1), then selected as pivot node at lowest
level.
INSERTION
General algorithm for insertion

## 1. Insert similarly to binary search tree

2. Check for balancing factor
3. If balancing factor of any node =  2
i. Find pivot node
ii. Do rotation at pivot node.

## Insertion can be done in,

1) Left sub tree of Left child of pivot node SINGLE RIGHT ROTATION
2) Right sub tree of Right child of pivot node SINGLE LEFT ROTATION

3) Left sub tree of Right child of pivot nod LEFT RIGHT ROTATION
4) Right sub tree of Left child of pivot node RIGHT LEFT ROTATION

## SINGLE RIGHT ROTATION

SINGLE LEFT ROTATION Mirror image of each other

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
44
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

## When insertion in left sub tree of left child of pivot node.

Before insertion:

S bf (S) =h +1 - h = 1

bf (M) = h – h = 0
M Right
sub
tree h
Left Right of S
sub h h sub
tree tree
of M of M

In the given above tree, the balancing factor of each and every node in the tree is
in balanced condition. So, there is no change .If we add or insert a new node in the left
sub tree of left child, then it becomes unbalanced so you have rotate the nodes to become
balanced tree. This can be done through Single right rotation in the following paragraphs.

After insertion:
bf (S)=h+1+1-h = 2
S K1 pivot node

bf (M)=h+1-h=1 K2 Right
M
sub tree
of h
S
Left Right
sub tree sub
h+1 of h tree of
M M
Insertion
i

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
45
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

In the above tree, if we insert node in the left sub tree of left child, it becomes
unbalanced, node S balance factor is 2 and it should be noted as pivot node and make the
right rotation to bring as balanced tree. The balanced tree after single right rotation as
given below. Here the pointer rotation can be mentioned in the box below.

After rotation
bf (M)=h+1 - ( h+ 1) = 0
M

bf (S)=h-h=0
S
Left
sub tree
h+1 of
M
Insertion Older Right
i Right sub tree
h sub of h
tree of S
M

## So the rotation can be mentioned as

K2 = K1 Left
K1 Left = K2 Right
K2 Right = K1

## SINGLE LEFT ROTATION

When insertion is done in right sub tree of right child of pivot node In the given
below tree, the balancing factor of each and every node in the tree is in balanced
condition. So, there is no change .If we add or insert a new node in the right sub tree of
right child, then it becomes unbalanced so you have rotate the nodes to become balanced
tree. This can be done through Single left rotation in the following paragraphs.

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
46
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

Before insertion
bf (M)=h - ( h+ 1) = - 1
M

bf (Q)=h-h=0
Q
Left
sub tree
h of
M
Left Right
sub tree sub tree
h of of h
Q Q

After insertion:

K1 bf (M)=h - ( h+ 1+1) = - 2
M pivot node

bf (Q)=h- (h+1) = -1
K2 Q
Left
sub tree
h of
M
Left Right sub
sub tree tree of
h of Q h+1
Q
Insertion

In the above tree, if we insert node in the right sub tree of right child, it becomes
unbalanced, node M balance factor is 2 and it should be noted as pivot node and make the
left rotation to bring as balanced tree. The balanced tree after single left rotation as given
below. Here the pointer rotation can be mentioned in the box below.

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
47
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

After rotation:

Q bf (Q) =h +1 – ( h+1) = 0

bf (M) = h – h = 0
M Right
sub tree
of Q
Insertion h+1
Left Older
sub tree h h Left
of sub tree
M of
Q

## So the rotation can be mentioned as

K2 = K1 Right
K1 Right = K2 Left
K2 Left = K1

DOUBLE ROTATION

##  LEFT RIGHT ROTATION (L R)

Mirror image of each other
 RIGHT LEFT ROTATION(R L)

## LEFT RIGHT ROTATION (L R)

When insertion is done in left sub tree of right child of pivot node.To understand
Left Right Rotation (LR), we can consider the given tree; the balancing factor of each and
every node in the tree is in balanced condition. So, there is no change .If we add or insert
a new node in the, left sub tree of right child then it becomes unbalanced so you have
rotate the nodes to become balanced tree. The insertion may be either in left child or right
child of left sub tree only.

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
48
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

Before insertion:

K1 bf (S)=(h+1)- (h+2) = -1
S

bf (V)=(h+1) –h =1
K2 V
Left
sub tree
h+1 of
S T bf (T) = h - h
=0 Right
sub tree h
of
Left Right V
h sub tree h sub tree
of of
T T

After insertion:

K1 bf (S)=h + 1- (h+3) = -2
S pivot node

bf (V)=(h+2) –h =2
K2 V pivot node
Left
sub tree
h+1 of
S T bf (T) = h +1- h Right
=1
sub tree h
of
Left Right V
sub tree h sub tree
of of
h+1 T T

Insertion

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
49
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

Consider Right sub tree shown below can be rotated in single right rotation this is as
follows.
Before insertion:
bf (V) = h+1+1-h = 2
V

bf (T)=h+1-h
T =1
Right
sub tree h
of
Right V
Left
sub tree
sub tree h
of
of h+1
T
T

Insertion

(RIGHT)

## After right rotation:

Left V
sub tree
of h+1
T Older Right
Right sub tree
Insertion sub tree h of h
of V
T

After right rotation, you have to make left rotation to get balanced tree. This is given as
below

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
50
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

## T bf (T) =h+1 - (h+1) =0

Left
sub tree
of
bf (V) = h – h =0
S
V
Left
sub tree
of
h+1
T Older Right
Right sub tree
Insertion sub tree of
h h
of V
T

(LEFT)

## T bf (T) =h+1 - (h+1) =0

bf (V) = h – h =0
bf(S)=h-(h+1)=-1 V
S

Older Right
Right sub tree
Left Older sub tree of
h h
sub tree Left of V
of sub tree T
h
S of
T
h+1
Insertion

## RIGHT LEFT ROTATION (R L)

When insertion is done in Right sub tree of Left child of pivot nodeTo understand
Right Left Rotation (RL), we can consider the given tree; the balancing factor of each and
every node in the tree is in balanced condition. So, there is no change .If we add or insert
a new node in the, right sub tree of left child then it becomes unbalanced so you have
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
51
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

rotate the nodes to become balanced tree.The insertion may be either in left child or right
child of right sub tree only.

Before insertion:
bf (S)=h+2-(h+1)
S

bf(M)=h+1-(h+1)
M Right
sub tree h+1
bf (Q)=h-h of
Q =0 S

Left
sub tree
h+1 of Left Right
M h sub tree sub tree h
of of
Q Q

After insertion:

bf (S)=h+3-(h+1)=2
S

bf(M)=h+1-(h+2)=-1
M Right
sub tree h+1
of
bf(Q)=h+1-h=1 Q S

Left
sub tree
h+1 Left Right
of
h+1 sub tree sub tree h
M
of Q of
Q
Insertion

Consider Left sub tree shown below can be rotated in single right rotation this is as
follows.

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
52
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

Before insertion:

M Bf(M)=h-h-2=-2

bf(Q)=h+1-h=1
Q
Left
h sub tree
of
T
Right Right
sub tree sub tree h
of of
h+1 Q Q
Insertion

(LEFT)
After right rotation:

Right
sub tree h
Left Older of
sub tree Left Q
of h sub tree
M of h+1
Q
Insertion

After left rotation, you have to make right rotation to get balanced tree. This is given as
below

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
53
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

S

Right
M Sub tree
h+1
of
Right S
sub tree h
Left Older of
sub tree Left Q
of h sub tree
M of h+1
Q
Insertion

(RIGHT)

## Q bf (Q) =h+2 - (h+1) =1

bf (S) = h – h =0
bf(M)=h-(h+1)=-1 S
M

Older Right
Right sub tree
Left Older sub tree of
h h
sub tree Left of S
of sub tree Q
h
M of
Q
h+1
Insertion

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
54
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

## 8)a)Write a function to perform Delete Min in a binary heap.

(May/Jun 05) (OR)
b)How to create a heap-ordered tree. Explain it with suitable
example.(OR)
c)Explain the Basic heap operations in detail.(OR)
d)Illustrate inserting an element into a heap with the given
elements.(Nov/Dec 05)

## Basic Heap operation:

It is easy to perform the two required operations. All the work involves ensuring
that the heap order property is maintained.

Insert:
To insert an element X in the heap, we create a hole in the next available location,
since otherwise the tree will not be complete. If X can be placed in the hole without
violation heap order, then we do so and are done. Otherwise we slide the element that is
in the whole’s parent node into the hole, thus bubbling the hole up towards the root. We
continue this process until X can be placed in a hole. Figure shows that to insert 14, we
create a hole would violate the heap order property; so 31 are slid down into the hole.
This strategy is continued in figure until the correct location in figure, until the correct
location for 14 is found.
This general strategy is known as a percolate up; the new element is percolated up
the heap until the correct location is found.

1
3

2 1
1 6

2 3 1 6
4 1 9 8

6 2 3
5 6 2

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
55
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

Attempt to insert 14: Create the hole, and bubbling the hole up

13

16
21

68
24 19

65 26 32 31

1
3

1
6

6
2 2 1 8
4 1 9

6
5 2 3 3
6 2 1

## Fig: The remaining two steps to insert 14 in previous heap

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
56

6 2 3 3
5 6 2 1
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

Delete _ min:
Delete _ min are handled in a similar manner as insertions. Finding the minimum is
easy, the hard part is removing it. When the minimum is removed, a hole is created at the
root. Since the heap now becomes one smaller, it follows that the last element in the heap
must move somewhere in the heap. If the last element can be placed in the hole, then we
are done. This is unlikely, so we slide the smaller of the hole’s children into the hole, thus
pushing the hole down one level. We repeat this step until the last element can be placed
in the hole. Thus, our action is to place the last element in this occur spot along a path
from the root containing minimum children

In figure, the left figure shows a heap prior to the Delete_Min. After 13 is
removed, we must now try to place 31 in heap. 31cannot are placed in the hole, because
this would violate heap order. Thus we place the smaller child (14) in the hole, sliding the
hole down one level. We repeat this again, placing 19 into the hole and creating a new
hole one level deeper. We then place 26 in the hole and create a new hole on the bottom
level. Finally, we are able to place 31 in the hole. This general strategy is known as a
Percolate down. We use the same technique as in the Insert routine to avoid the use of
swaps in this routine.

## PRIORITY QUEUE (HEAPS)

The priority queue is a data structure in which the intrinsic ordering of the
elements does determine the results of its basic operations. There are two types of
priority queue.
1. Ascending priority queue.
2. Descending priority queue.

## Ascending priority queue:

It’s a collection of item into which items can be inserted arbitrarily & from which
only the smallest item can be removed.

## Descending priority queue:

It’s similar but allows deletion of only the largest item. The operations applicable
to a descending priority queue.

 In multi user environment, the operating system scheduler must decide which of
several processes to run.
 Process is allowed to run only for a fixed period of time.
One algorithm uses a queue. Jobs are initially placed at the end of the queue. This
scheduler will repeatedly take the first job on the queue, if it does not finish. This strategy
is generally not appropriate, because very short job will seem to take a long time because
of the wait involved to run.
This particular application seems to require a special kind of queue known as a
priority queue. We will discuss
1. Efficient implementation of the ADT priority queue.
2. Uses of priority queue.
3. Advanced implementations of priority queue.
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
57
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

## Priority queue model

A priority queue is a data structure that allows at least the following two operations:
 Insert
 Delete _ min
Insert:
The insert operation is the equivalent of Enqueue.

Delete _ min
Delete _ min is the priority queue equivalent of the queue’s Dequeue operation.
As with most data structures, it is sometimes possible to ad other operations, but these are
extensions and not part of the basic model in the following figure.

PRIORITY QUEUE

## Basic model a priority queue

Priority queues have many applications besides operating systems. Priority queues
are also important in the implementation of greedy algorithms, which operate by
repeatedly finding a minimum will see the use of priority queues is discrete event
simulation.

Simple implementations:

There are several obvious ways to implementation a priority queue. We could use a
simple linked list, performing insertion at the front in 0(1) and traversing the list, which
requires 0(n) time, to delete the minimum.

We could insist that the list be always kept sorted; this makes insertions expensive
(0(n)) and Delete_mins cheap (o(1)). The format is probably the better idea of the two,
based on the fact that there are never more Delete_mins than insertions.

Priority queues would be to use a binary search tree. This gives an 0(log n)
average running time for both operations.

The Delete_min have deleted the left sub tree, the right sub tree would have at
most twice as many elements as it should. This adds only a small constant to its excepted
depth.
The basic data structure we will use will not require pointer and will support both
operations in 0(log n) worst-case time. Insertion will actually take constant time an
average, and our implementation will allow building a priority queue of n items in linear
time if no deletions intervene.

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
58
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

Binary Heap:
Binary heaps merely heaps. Like binary search trees, heaps have two properties,
namely,
 Structure property.
 Heap property.

Structure Property
A heap is a binary tree that is completely filled, with the possible exception of the
bottom level, which is filled from left to right. Such a tree is known as a complete binary
tree. Figure shows in the following section.
It is easy to show that a complete binary tree of height h has between 2h and
2h+1 – 1 nodes. This implies that the height of a complete binary tree is (log n),
which is clearly 0(log n).
An important observation is that because a complete binary tree is so regular, it
can be represented in an array and no pointers are necessary. This array & corresponding
to the heap figure in the following section.

B C

D E F G

H
I J

## A complete Binary tree

A B C D E F G H I J

0 1 2 3 4 5 6 7 8 9 10 11 12
Array implementation of complete binary tree

For any element in the array position I, the left child is in position 2i, the right
child is in the cell after the left child (2i+1), and the parent is in position (i/2). Thus, not
only are pointer not required, but the operations required to traverse the tree are
extremely simple and likely to be very fast on most computers. The only problem with
this implementation is that an estimate of the maximum heap size is required in advance,
but typically this not a problem. In the figure, the limit on the heap size is 13 elements.
The array has a position 0.

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
59
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

## Heap Order Property

The property that allows operations to be performed quickly is the heap order
property. Since we want to be able to find the minimum quickly, it makes sense that the
smallest element should be at the root. If we consider that any sub tree should also be a
heap, then any node should be smaller than all of its descendants.
Applying this logic, we arrive at the heap order property. In an heap, for every
node X, the key in the parent of X is smaller than the key in X, with the obvious
exception of the root. The tree on the left is a heap, but the tree on the right is not the
dashed line shows the violation of heap order.

1
3

2
1 1
6

2
4 3 1 6
1 9 8

6
5 2
6 3
2

1
3

2 1
1 6

6
3 1 6
1 9 8

6
5 2 3
6 2

By the heap order property, the minimum element can always be found at the root. Thus
we get the extra operation, Find _ Min in constant time.

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
60
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

## 9. Explain B-Tree with Example. Give an algorithm for insert an element in

B-tree.
Insertion into a B-Tree
To insert value X into a B-tree, there are 3 steps:
Using the SEARCH procedure for M-way trees (described above) find the leaf node to
which X should be added.
1. add X to this node in the appropriate place among the values already there. Being
a leaf node there are no subtrees to worry about.
2. if there are M-1 or fewer values in the node after adding X, then we are finished.

If there are M nodes after adding X, we say the node has overflowed. To repair
this, we split the node into three parts:

Left:
the first (M-1)/2 values
Middle:
the middle value (position 1+((M-1)/2)
Right:
the last (M-1)/2 values

Notice that Left and Right have just enough values to be made into individual
nodes. That's what we do... they become the left and right children of Middle, which we
add in the appropriate place in this node's parent.

But what if there is no room in the parent? If it overflows we do the same thing
again: split it into Left-Middle-Right, make Left and Right into new nodes and add
Middle (with Left and Right as its children) to the node above. We continue doing this
until no overflow occurs, or until the root itself overflows. If the root overflows, we split
it, as usual, and create a new root node with Middle as its only value and Left and Right
as its children (as usual).

For example, let's do a sequence of insertions into this B-tree (M=5, so each node other
than the root must contain between 2 and 4 values):

## Insert 17: Add it to the middle leaf. No overflow, so we're done.

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
61
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

## Insert 6: Add it to the leftmost leaf. That overflows, so we split it:

 Left = [ 2 3 ]
 Middle = 5
 Right = [ 6 7 ]

Left and Right become nodes; Middle is added to the node above with Left and Right as
its children.

The node above (the root in this small example) does not overflow, so we are done.

Insert 21: Add it to the middle leaf. That overflows, so we split it:

 left = [ 17 21 ]
 Middle = 22
 Right = [ 44 45 ]

Left and Right become nodes; Middle is added to the node above with Left and Right as

its children.

The node above (the root in this small example) does not overflow, so we are done.

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
62
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

Insert 67: Add it to the rightmost leaf. That overflows, so we split it:

 Left = [ 55 66 ]
 Middle = 67
 Right = [ 68 70 ]

Left and Right become nodes; Middle is added to the node above with Left and Right as
its children.

But now the node above does overflow. So it is split in exactly the same manner:
 Left = [ 5 10 ] (along with their children)
 Middle = 22
 Right = [ 50 67 ] (along with their children)

Left and Right become nodes, the children of Middle. If this were not the root,
Middle would be added to the node above and the process repeated. If there is no node
above, as in this example, a new root is created with Middle as its only value.

The tree-insertion algorithms we're previously seen add new nodes at the bottom
of the tree, and then have to worry about whether doing so creates an imbalance. The B-
tree insertion algorithm is just the opposite: it adds new nodes at the top of the tree (a new
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
63
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

node is allocated only when the root splits). B-trees grow at the root, not at the leaves.
Because of this, there is never any doubt that the tree is always perfectly height balanced:
when a new node is added, all existing nodes become one level deeper in the tree.

## Inserting Items into a B-Tree

The algorithm for insertion into a B-Tree begins as do all the other search tree insertion
algorithms: To insert item x, we begin at the root and conduct a search for it. Assuming
the item is not already in the tree, the unsuccessful search will terminate at a leaf node.
This is the point in the tree at which the x is inserted.

If the leaf node has fewer than M-1 keys in it, we simply insert the item in the leaf node
and we are done. For example, consider a leaf node with n<M subtrees and n-1 keys of
the form

For every new key inserted in the node, a new subtree is required too. In this case
because T is a leaf, all its subtrees are empty trees. Therefore, when we insert item x, we
really insert the pair of items . Suppose the key to be inserted falls between and
, i.e., . When we insert the pair into T we get the new leaf T' given
by

What happens when the leaf is full? That is, suppose we wish to insert the pair, into
a node T which already has M-1 keys. Inserting the pair in its correct position gives a
result of the form

However, this is not a valid node in a B-tree of order M because it has M+1 subtrees and
M keys. The solution is to split node T' in half as follows

## Note, is a valid B-tree node because it contains subtrees and keys.

Similarly, is a valid B-tree node because it contains subtrees and
keys. Note that there is still a key left over, namely .

There are now two cases to consider--either T is the root or it is not. Suppose T is not the
root. Where we once had the single node T, we now have the two nodes, and , and
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
64
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

the left-over key, . This situation is resolved as follows: First, replaces T in the
parent of T. Next, we take the pair and recursively insert it in the parent of T.

Figure illustrates this case for a B-tree of order three. Inserting the key 6 in the tree
causes the leaf node to overflow. The leaf is split in two. The left half contains key 5; and
the right, key 7; and key 6 is left over. The two halves are re-attached to the parent in the
appropriate place with the left-over key between them.

## Figure: Inserting items into a B-tree (insert 6).

If the parent node fills up, then it too is split and the two new nodes are inserted in the
grandparent. This process may continue all the way up the tree to the root. What do we do
when the root fills up? When the root fills, it is also split. However, since there is no
parent into which to insert the two new children, a new root is inserted above the old root.
The new root will contain exactly two subtrees and one key, as allowed by Definition .

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
65
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

Figure illustrates this case for a B-tree of order three. Inserting the key 3 in the tree
causes the leaf node to overflow. Splitting the leaf and reattaching it causes the parent to
overflow. Similarly, splitting the parent and reattaching it causes the grandparent to
overflow but the grandparent is the root. The root is split and a new root is added above
it.

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
66
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

## Figure: Inserting items into a B-tree (insert 3).

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
67
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

Notice that the height of the B-tree only increases when the root node splits. Furthermore,
when the root node splits, the two halves are both attached under the new root. Therefore,
the external nodes all remain at the same depth, as required by Definition

## 10.Explain the concept of splay tree with suitable example?

 These are binary search trees which are self-adjusting in the following way:

Every time we access a node of the tree, whether for retrieval or insertion or
deletion, we perform radical surgery on the tree, resulting in the newly accessed
node becoming the root of the modified tree. This surgery will ensure that nodes
that are frequently accessed will never drift too far away from the root whereas
inactive nodes will get pushed away farther from the root.

 Amortized complexity

 Splay trees can become highly unbalanced so that a single access to a node
of the tree can be quite expensive.

 However, over a long sequence of accesses, the few expensive cases are
averaged in with many inexpensive cases to obtain good performance.

 Does not need heights or balance factors as in AVL trees and colours as in Red-
Black trees.

 The surgery on the tree is done using rotations, also called as splaying steps.
There are six different splaying steps.

## 1. Zig Rotation (Right Rotation)

2. Zag Rotation (Left Rotation)
3. Zig-Zag (Zig followed by Zag)
4. Zag-Zig (Zag followed by Zig)
5. Zig-Zig
6. Zag-Zag
 Consider the path going from the root down to the accessed node.

 Each time we move left going down this path, we say we ``zig'' and
each time we move right, we say we ``zag.''

## Figure 4.17: Zig rotation and zag rotation

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
68
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

## Figure 4.19: Zag-zig rotation

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
69
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

## Figure 4.20: Zig-zig and zag-zag rotations

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
70
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

##  Zig Rotation and Zag Rotation

o Note that a zig rotation is the same as a right rotation whereas the zag step
is the left rotation.
o See Figure 4.17.
 Zig-Zag
o This is the same as a double rotation in an AVL tree. Note that the target
element is lifted up by two levels.
o See Figure 4.18.
 Zag-Zig
o This is also the same as a double rotation in an AVL tree.
o Here again, the target element is lifted up by two levels.
o See Figure 4.19.
 Zig-Zig and Zag-Zag
o The target element is lifted up by two levels in each case.
o Zig-Zig is different from two successive right rotations; zag-zag is
different from two successive left rotations. For example, see Figures 4.20,
and 4.21.
 See Figure 4.22 for an example

## Figure 4.22: An example of splaying

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
71
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

##  The above scheme of splaying is called bottom-up splaying.

 In top-down splaying, we start from the root and as we locate the target element
and move down, we splay as we go. This is more efficient.

PART-C
ASSIGNMENT QUESTIONS
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
72
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

2 MARK QUESTIONS
1. Illustrate the array representation for a binary tree.
2. Differentiate between complete binary tree and full binary tree.
3. Write an algorithm for In order traversal of binary trees.
4. Prove that a binary tree with n nodes has exactly n+ 1 null branch.
5. Give the three cases involved in deleting a node from a binary search tree.
6. What is the significance of threaded binary tree?
7. Construct binary tree for the following infix expression A+B *C/D
8. Perform Post order traversal for the following binary tree.
9.Give various implementation of tree.
10. Define : Binary tree
11.Create a binary tree for the following expression ((d*e+f)*g)
12.Define complete binary tree.
13. How is binary tree represented using an array? Give an example.
14.Define binary search tree.
15.Show that the maximum number of nodes in a binary tree of height H is 2H+1-1.
16.Convert the infix expression a+b*c+(d*c+f)*g to its equivalent postfix expression.
17.A full node is a node with two children .Prove that the number of full nodes plus one
is equal to the number of leaves in a non empty binary tree.
18.List ourt the steps involved in deleting a node from a binary search tree.
19.
20.Define siblings with example.
21. Write the application of expression tree.
22.Write the rules for the construction of Binary Search Tree.
23.How to find the parent. Left child and right child of Nodes?
24.Why it is said that the searching a node in a binary search tree is efficient than that of
a simple binary tree?
25.What is left and right skewed tree?

12 MARK QUESTIONS
1. Give and explain the various tree traversal algorithms with example.(Nov/Dec’03,’04)
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
73
SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES

## 2. Write an algorithm to locate an element from binary search tree (Nov/Dec’05)

3. Write the routines to insert and remove a node from binary search tree.(Nov/Dec’07)
4. Draw a binary search tree for the following input list 60, 25,75,15,50,66,33,44.
Trace the algorithm to delete the nodes 25,75,44 from the tree.(Nov/Dec’05)
5. How do you insert an element in a binary search tree?(Nov/Dec’05)
6. Show that for perfect binary tree of height H containing 2H+1-1 nodes, the sum of the
a height of the nodes is 2H+1-1-1(H+1). (Nov/Dec’05)
7. Write an algorithm to create a empty binary tree and to search for an element ‘X’ in
it.(Apr/May’07)
8. Explain the manipulation of arithmetic expression with the help of a tree with suitable
examples.(Nov’03)
9. Explain in detail about threaded binary tree with example?
10. What are the applications of binary tree data structured and explain (May’07)

SENGUNTHAR ENGG COLLEGE, TGODE / DEPT OF CSE / DATA STRUCTURES / UNIT II & III/ TREE STRUCTURES & BALANCED TREES
74