0% found this document useful (0 votes)
43 views24 pages

Pds ch-3 Print

Uploaded by

nanda22051978
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views24 pages

Pds ch-3 Print

Uploaded by

nanda22051978
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

PDS CHAPTER-3 TREES

PART-A
1.If the depth of binary tree is k, the maximum number of nodes in the binary tree is 2k -1.
Prove.
Considering the definition of height : the leaf has height 0 and it increases at every
level.
height(node) = max(height(node.right),height(node.left))+1
and height(node) = -1, if node = null
x=(h+1)x=(h+1)
then maximum number of nodes = 2x−12x−1
if you take the definition of height as : the leaf has height 1.
height(node) = max(height(node.right),height(node.left))+1
and height(node) = 0, if node = null
Then the maximum number of nodes = 2^k−1
2. Recommend the result of inserting 3, 1, 4, 6, 9, 2, 5, 7 into an initially empty binary search
tree.

3.Define a binary tree. Give an example


A binary tree is a tree-type non-linear data structure with a maximum of two
children for each parent. Every node in a binary tree has a left and right reference along with
the data element. The node at the top of the hierarchy of a tree is called the root node. The
nodes that hold other sub-nodes are the parent nodes.
4. Create an expression tree for the expression. ((a + ((b/c)*d))- e).

5.Differentiate AVL tree and Binary search tree.

6. Give the various types of rotations in AVL tree during the insertion of a node?
Left Rotation (LL Rotation)
Right Rotation (RR Rotation)
Left-Right Rotation (LR Rotation)
Right-Left Rotation (RL Rotation)
7.What are threaded binary trees? Give its advantages.
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.
Advantage
By doing threading we avoid the recursive method of traversing a Tree , which makes use of
stack and consumes a lot of memory and time .
The node can keep record of its root .
8. Define balance factor of AVL Tree.
An AVL Tree is a height-balanced binary search tree. The balance factor of a binary tree
is the difference in heights of its two subtrees (hR - hL). The balance factor (bf) of a height
balanced binary tree may take on one of the values -1, 0, +1.
9. Simulate the result of inserting 2, 1, 4, 5, 9, 3, 6, 7 into an initially empty AVL Tree.

10. Define an expression tree. Give an example for it.


Expression tree as name suggests is nothing but expressions arranged in a tree-like
data structure. Each node in an expression tree is an expression. For example, an
expression tree can be used to represent mathematical formula x < y where x, < and y
will be represented as an expression and arranged in the tree like structure.
11. Summarize tree traversal and mention the type of traversals?
tree traversal (also known as tree search and walking the tree) is a form of graph
traversal and refers to the process of visiting (e.g. retrieving, updating, or deleting) each node
in a tree data structure, exactly once. Such traversals are classified by the order in which the
nodes are visited.
There are 3 types of traversals:
Inorder Traversal
Preorder Traversal
Postorder Traversal
12. Differentiate B tree and B+ tree.

13. For the given tree


i. List the siblings for node E
ii. Compute the height.

i)The siblings of the node E are D and F.


ii)The height of the given tree is 4.
14. Point out the properties of B+ tree.
Properties of a B+ Tree
All leaves are at the same level.
The root has at least two children.
Each node except root can have a maximum of m children and at least m /2 children.
Each node can contain a maximum of m - 1 keys and a minimum of ⌈m/2⌉ - 1 keys.
15. Illustrate the benefits of B+ tree.
Benefits of B+ Tree:
Records can be fetched in equal number of disk accesses.
Height of the tree remains balanced and less as compare to B tree.
We can access the data stored in a B+ tree sequentially as well as directly.
Keys are used for indexing.
Faster search queries as the data is stored only on the leaf nodes.
16. List out the various operations that can be performed on B-trees.
A B-Tree is a special kind of tree in a data structure. It helps you to preserves data sorted
and allowed various operations like Insertion, searching, and deletion in less time.
17. Identify the structural properties of B-Trees.
the structural properties of B-Trees:
Every node in a B-Tree contains at most m children.
Every node in a B-Tree except the root node and the leaf node contain at least m/2 children.
The root nodes must have at least 2 nodes.
All leaf nodes must be at the same level.
18.not found
19. Analyze the properties of binary heap.
The ordering can be one of two types:
The min-heap property: the value of each node is greater than or equal to the value of its
parent, with the minimum-value element at the root.
The max-heap property: the value of each node is less than or equal to the value of its
parent, with the maximum-value element at the root.
20. Define a heap and show how it can be used to represent a priority queue.
Priority-queue. Heaps: A heap is a specific tree based data structure in which all the nodes
of tree are in a specific order. Let's say if X is a parent node of Y, then the value of X follows
some specific order with respect to value of Y and the same order will be followed across
the tree.
PART-B
1.Write an algorithm for preorder, inorder and postorder traversal of a binary tree.
Algorithm for Traversal of a Binary Tree (Inorder, Preorder and Postorder)
Algorithm for in-order traversal
Step 1: Repeat Steps 2 to 4 while TREE != NULL
Step 2: INORDER(TREE LEFT)
Step 3: Write TREE DATA
Step 4: INORDER(TREE RIGHT) [END OF LOOP]
Step 5: END
Explanation
The in-order traversal of the tree is given as B, A, and C.
Left sub-tree first, the root node next, and then the right sub-tree.
In-order traversal is also called as symmetric traversal.
In this algorithm, the left sub-tree is always traversed before the root node and the right sub-
tree.
The word ‘in’ in the in-order specifies that the root node is accessed in between the left and
the right sub-trees.
In-order algorithm is also known as the LNR traversal algorithm (Left-Node-Right).
In-order traversal algorithm is usually used to display the elements of a binary search tree.
Algorithm for pre-order traversal
Step 1: Repeat Steps 2 to 4 while TREE != NULL
Step 2: Write TREE DATA
Step 3: PREORDER(TREE LEFT)
Step 4: PREORDER(TREE RIGHT) [END OF LOOP]
Step 5: END
Explanation
The pre-order traversal of the tree is given as A, B, C.
Root node first, the left sub-tree next, and then the right sub-tree.
Pre-order traversal is also called as depth-first traversal. In this algorithm, the left sub-tree is
always traversed before the right sub-tree.
The word ‘pre’ in the pre-order specifies that the root node is accessed prior to any other
nodes in the left and right sub-trees.
Pre-order algorithm is also known as the NLR traversal algorithm (Node-Left-Right).
Pre-order traversal algorithms are used to extract a prefix notation from an expression tree.
Algorithm for post-order traversal
Step 1: Repeat Steps 2 to 4 while TREE != NULL
Step 2: POSTORDER(TREE LEFT)
Step 3: POSTORDER(TREE RIGHT)
Step 4: Write TREE DATA [END OF LOOP]
Step 5: END
Explanation
The post-order traversal of the tree is given as B, C, and A.
Left sub-tree first, the right sub-tree next, and finally the root node.
In this algorithm, the left sub-tree is always traversed before the right sub-tree and the root
node.
The word ‘post’ in the post-order specifies that the root node is accessed after the left and
the right sub-trees.
Post-order algorithm is also known as the LRN traversal algorithm (Left-Right-Node).
Post-order traversals are used to extract postfix notation from an expression tree.
2. Explain the following operations on a binary search tree with suitable algorithm
i) Find a node (7)
ii) Find minimum and maximum elements of BST.
i) Algorithm to find a node:
Define Node class which has three attributes namely: data left and right. Here, left
represents the left child of the node and right represents the right child of the node.
When a node is created, data will pass to data attribute of the node and both left and right
will be set to null.
Define another class which has two attribute root and flag.
Root represents the root node of the tree and initializes it to null.
The Flag will be used to check whether the given node is present in the tree or not. Initially, it
will be set to false.
searchNode() will search for a particular node in the binary tree:
It checks whether the root is null, which means the tree is empty.
If the tree is not empty, it will compare temp?s data with value. If they are equal, it will set the
flag to true and return.
Traverse left subtree by calling searchNode() recursively and check whether the value is
present in left subtree.
Traverse right subtree by calling searchNode() recursively and check whether the value is
present in the right subtree.
Explanation:
For Finding Minimum value in Binary search tree.
start from root i.e 8.

As left of root is not null go to left of root i.e 3. As left of 3 is not null go to left of 3 i.e. 1.
Now as the left of 1 is null therefore 1 is the minimum element

For Finding Maximum value in Binary search tree.


start from root i.e 8.

As right of root is not null go to right of root i.e 10.

As right of 10 is not null go to right of root i.e 13.

As right of 13 is not null go to right of root i.e 14.


Now as the right of 14 is null therefore 14 is the maximum element.

3.Write an algorithm for inserting and deleting a node in a binary search tree.
INSERTION:

Algorithm
Delete (TREE, ITEM)
Step 1: IF TREE = NULL
Write "item not found in the tree" ELSE IF ITEM < TREE -> DATA
Delete(TREE->LEFT, ITEM)
ELSE IF ITEM > TREE -> DATA
Delete(TREE -> RIGHT, ITEM)
ELSE IF TREE -> LEFT AND TREE -> RIGHT
SET TEMP = findLargestNode(TREE -> LEFT)
SET TREE -> DATA = TEMP -> DATA
Delete(TREE -> LEFT, TEMP -> DATA)
ELSE
SET TEMP = TREE
IF TREE -> LEFT = NULL AND TREE -> RIGHT = NULL
SET TREE = NULL
ELSE IF TREE -> LEFT != NULL
SET TREE = TREE -> LEFT
ELSE
SET TREE = TREE -> RIGHT
[END OF IF]
FREE TEMP
[END OF IF]
Step 2: END
For deleting a node

4. Describe the concept of threaded binary tree with example.


Threaded Binary Tree
In the linked representation of binary trees, more than one half of the link fields contain
NULL values which results in wastage of storage space. If a binary tree consists of n nodes
then n+1 link fields contain NULL values. So in order to effectively manage the space, a
method was devised by Perlis and Thornton in which the NULL links are replaced with
special links known as threads. Such binary trees with threads are known as threaded
binary trees. Each node in a threaded binary tree either contains a link to its child node or
thread to other nodes in the tree.

Types of Threaded Binary Tree


There are two types of threaded Binary Tree:
One-way threaded Binary Tree
Two-way threaded Binary Tree
One-way threaded Binary trees:

In one-way threaded binary trees, a thread will appear either in the right or left link field of a
node. If it appears in the right link field of a node then it will point to the next node that will
appear on performing in order traversal. Such trees are called Right threaded binary trees. If
thread appears in the left field of a node then it will point to the nodes inorder predecessor.
Such trees are called Left threaded binary trees.
Two-way threaded Binary Trees:

In two-way threaded Binary trees, the right link field of a node containing NULL values is
replaced by a thread that points to nodes inorder successor and left field of a node
containing NULL values is replaced by a thread that points to nodes inorder predecessor.

In the above figure of two-way threaded Binary tree, we noticed that no left thread is
possible for the first node and no right thread is possible for the last node. This is because
they don't have any inorder predecessor and successor respectively. This is indicated by
threads pointing nowhere. So in order to maintain the uniformity of threads, we maintain a
special node called the header node. The header node does not contain any data part and
its left link field points to the root node and its right link field points to itself. If this header
node is included in the two-way threaded Binary tree then this node becomes the inorder
predecessor of the first node and inorder successor of the last node. Now threads of left
link fields of the first node and right link fields of the last node will point to the header node.
Advantages of Threaded Binary Tree:
In threaded binary tree, linear and fast traversal of nodes in the tree so there is no
requirement of stack. If the stack is used then it consumes a lot of memory and time.
Disadvantages of Threaded Binary Tree:
When implemented, the threaded binary tree needs to maintain the extra information for
each node to indicate whether the link field of each node points to an ordinary node or the
node's successor and predecessor.
Discuss in detail the various methods in which a binary tree can be represented. Discuss
the advantage and disadvantage of each method.
Binary trees:
Every parent or node in binary trees can have a maximum of only two children.
All nodes in a binary tree have three primary components –
a data element
a right reference
a left reference
Representation of binary trees
1. Linked representation
Binary trees in linked representation are stored in the memory as linked lists. These lists
have nodes that aren’t stored at adjacent or neighboring memory locations and are linked to
each other through the parent-child relationship associated with trees.
In this representation, each node has three different parts –
pointer that points towards the right node,
pointer that points towards the left node,
data element.
This is the more common representation. All binary trees consist of a root pointer that points
in the direction of the root node. When you see a root node pointing towards null or 0, you
should know that you are dealing with an empty binary tree. The right and left pointers store
the address of the right and left children of the tree.
2. Sequential representation
Although it is simpler than linked representation, its inefficiency makes it a less preferred
binary tree representation of the two. The inefficiency lies in the amount of space it requires
for the storage of different tree elements. The sequential representation uses an array for
the storage of tree elements.
The number of nodes a binary tree has defines the size of the array being used. The root
node of the binary tree lies at the array’s first index. The index at which a particular node is
stored will define the indices at which the right and left children of the node will be stored.
An empty tree has null or 0 as its first index.
Types of binary trees
Full binary trees: Full binary trees are those binary trees whose nodes either have two
children or none. In other words, a binary tree becomes a full binary tree when apart from
leaves, all its other nodes have two children.
Complete binary trees: Complete binary trees are those that have all their different levels
completely filled. The only exception to this could be their last level, whose keys are
predominantly on the left. A binary heap is often taken as an example of a complete binary
tree.
Perfect binary trees: Perfect binary trees are binary trees whose leaves are present at the
same level and whose internal nodes carry two children. A common example of a perfect
binary tree is an ancestral family tree.
Pathological degenerate binary trees: Degenerate trees are those binary trees whose
internal nodes have one child. Their performance levels are similar to linked lists.
Benefits of binary trees
An ideal way to go with the hierarchical way of storing data
Reflect structural relationships that exist in the given data set
Make insertion and deletion faster than linked lists and arrays
A flexible way of holding and moving data
Are used to store as many nodes as possible
Are faster than linked lists and slower than arrays when comes to accessing elements
Disadvantages:
It’s more complicated than linear search, and is overkill for very small numbers of elements.
It works only on lists that are sorted and kept sorted. That is not always feasable, especially
if elements are constantly being added to the list.
It works only on element types for which there exists a less-than relationship. Some types
simply cannot be sorted (though this is rare).
6.i) Create a binary search tree using the following data elements 45, 39, 56, 12, 34, 78, 32,
10, 89, 54, 67, 81
ii) Explain the steps to convert general tree to binary tree?

i)
ii)conversion of general tree into a Binary Tree by following below steps:
Given a Normal 3-ary (non-binary) tree
Insert an edge connecting all the sibling of the given n-ary tree.

Insert Edge connecting the siblings


Delete all the parent edges from the parent to its children except the one to its leftmost
child.

Delete all edges from a parent to its child except the leftmost one.
Rotate the resulting tree by 45degress to differentiate between its left and right subtree.

3-ary tree converted into a Binary Tree


The Time Complexity of converting an m-ary tree to Binary tree is O(N + E), N is the number
of nodes in the tree and E is the number of the edges in the intermediate tree created after
step 1.
Preorder, Inorder & Postorder of the resultant tree are
Preorder: V1, V2, V5, V6, V3, V4, V7, V9, V10, V11, V8
Inorder: V5, V6, V2, V3, V9, V10, V11, V8, V4, V1
Postorder: V6, V5, V11, V10, V9, V8, V7, V4, V3,V2, V1
i) Construct B Tree of order m=5 for the following keys 1, 12, 8, 2, 25, 5, 14, 28, 17, 7, 52, 16,
48, 68, 3, 26, 29, 53, 55, 45 (8)
ii) Delete the keys 8 and 55.State the rules for deletion. (5)
ii) the rules for deletion:
When we delete a node, three possibilities arise.
1) Node to be deleted is the leaf: Simply remove from the tree.
2) Node to be deleted has only one child: Copy the child to the node and delete the child
3) Node to be deleted has two children: Find inorder successor of the node. Copy contents
of the inorder successor to the node and delete the inorder successor. Note that inorder
predecessor can also be used.
Discuss how to insert an element in a AVL tree and explain with algorithm.
Insertion
Insertion in AVL tree is performed in the same way as it is performed in a binary search tree.
The new node is added into AVL tree as the leaf node. However, it may lead to violation in
the AVL tree property and therefore the tree may need balancing.
The tree can be balanced by applying rotations. Rotation is required only if, the balance
factor of any node is disturbed upon inserting the new node, otherwise the rotation is not
required.
Depending upon the type of insertion, the Rotations are categorized into four categories.

63, 9, 19, 27, 18, 108, 99, 81


The process of constructing an AVL tree from the given set of elements is shown in the
following figure.
At each step, we must calculate the balance factor for every node, if it is found to be more
than 2 or less than -2, then we need a rotation to rebalance the tree. The type of rotation will
be estimated by the location of the inserted element with respect to the critical node.
All the elements are inserted in order to maintain the order of binary search tree.
i)What are AVL trees? Describe the different rotations defined for AVL tree.
ii) Insert the following elements step by step in sequence into an empty AVL tree 63, 9, 19,
27, 18, 108, 99, 81.
i)It is observed that BST's worst-case performance is closest to linear search algorithms,
that is Ο(n). In real-time data, we cannot predict data pattern and their frequencies. So, a
need arises to balance out the existing BST.
Named after their inventor Adelson, Velski & Landis, AVL trees are height balancing binary
search tree. AVL tree checks the height of the left and the right sub-trees and assures that
the difference is not more than 1. This difference is called the Balance Factor.
Here we see that the first tree is balanced and the next two trees are not balanced −

In the second tree, the left subtree of C has height 2 and the right subtree has height 0, so
the difference is 2. In the third tree, the right subtree of A has height 2 and the left is missing,
so it is 0, and the difference is 2 again. AVL tree permits difference (balance factor) to be
only 1.
BalanceFactor = height(left-sutree) − height(right-sutree)
If the difference in the height of left and right sub-trees is more than 1, the tree is balanced
using some rotation techniques.
AVL Rotations
To balance itself, an AVL tree may perform the following four kinds of rotations −
Left rotation
Right rotation
Left-Right rotation
Right-Left rotation
The first two rotations are single rotations and the next two rotations are double rotations.
To have an unbalanced tree, we at least need a tree of height 2. With this simple tree, let's
understand them one by one.
Left Rotation
If a tree becomes unbalanced, when a node is inserted into the right subtree of the right
subtree, then we perform a single left rotation −

In our example, node A has become unbalanced as a node is inserted in the right subtree of
A's right subtree. We perform the left rotation by making A the left-subtree of B.
Right Rotation
AVL tree may become unbalanced, if a node is inserted in the left subtree of the left subtree.
The tree then needs a right rotation.

As depicted, the unbalanced node becomes the right child of its left child by performing a
right rotation.
Left-Right Rotation
Double rotations are slightly complex version of already explained versions of rotations. To
understand them better, we should take note of each action performed while rotation. Let's
first check how to perform Left-Right rotation. A left-right rotation is a combination of left
rotation followed by right rotation.
Right-Left Rotation
The second type of double rotation is Right-Left Rotation. It is a combination of right rotation
followed by left rotation.
ii) AVL tree 63, 9, 19, 27, 18, 108, 99, 81.

Analyze the operations of B-tree using 2-3 tree with example.


2-3 Trees | (Search and Insert)
2-3 tree is a tree data structure in which every internal node (non-leaf node) has either one
data element and two children or two data elements and three children. If a node contains
one data element leftVal, it has two subtrees (children) namely left and middle. Whereas if a
node contains two data elements leftVal and rightVal, it has three subtrees
namely left, middle and right.
The main advantage with 2-3 trees is that it is balanced in nature as opposed to a binary
search tree whose height in the worst case can be O(n). Due to this, the worst case time-
complexity of operations such as search, insertion and deletion is as the height of a 2-3 tree

is .
Base cases:
If T is empty, return False (key cannot be found in the tree).
If current node contains data value which is equal to K, return True.
If we reach the leaf-node and it doesn’t contain the required key value K, return False.
Recursive Calls:
If K < currentNode.leftVal, we explore the left subtree of the current node.
Else if currentNode.leftVal < K < currentNode.rightVal, we explore the middle subtree of
the current node.
Else if K > currentNode.rightVal, we explore the right subtree of the current node.
Consider the following example:

Insertion: There are 3 possible cases in insertion which have been discussed below:
Case 1: Insert in a node with only one data element

Case 2: Insert in a node with two data elements whose parent contains only one data
element.

Case 3: Insert in a node with two data elements whose parent also contains two data
elements.
Discuss about B+ tree in brief with suitable example.
A B+ Tree is primarily utilized for implementing dynamic indexing on multiple levels.
Compared to B- Tree, the B+ Tree stores the data pointers only at the leaf nodes of the
Tree, which makes search more process more accurate and faster.
Rules for B+ Tree
Here are essential rules for B+ Tree.
Leaves are used to store data records.
It stored in the internal nodes of the Tree.
If a target key value is less than the internal node, then the point just to its left side is
followed.
If a target key value is greater than or equal to the internal node, then the point just to its
right side is followed.
The root has a minimum of two children.
Uses of B+ Tree
Here, are reasons for using B+ Tree:
Key are primarily utilized to aid the search by directing to the proper Leaf.
B+ Tree uses a “fill factor” to manage the increase and decrease in a tree.
In B+ trees, numerous keys can easily be placed on the page of memory because they do
not have the data associated with the interior nodes. Therefore, it will quickly access tree
data that is on the leaf node.
A comprehensive full scan of all the elements is a tree that needs just one linear pass
because all the leaf nodes of a B+ tree are linked with each other.
B+ Tree
Search keys can be repeated.
Data is only saved on the leaf nodes.

Data stored on the leaf node makes the search more accurate and faster.

Deletion is not difficult as an element is only removed from a leaf node.

Linked leaf nodes make the search efficient and quick.

Insert Operation
The following algorithm is applicable for the insert operation:
50 percent of the elements in the nodes are moved to a new leaf for storage.
The parent of the new Leaf is linked accurately with the minimum key value and a new
location in the Tree.
Split the parent node into more locations in case it gets fully utilized.
Now, for better results, the center key is associated with the top-level node of that Leaf.
Until the top-level node is not found, keep on iterating the process explained in the above
steps.
Delete Operation
The complexity of the delete procedure in the B+ Tree surpasses that of the insert and
search functionality.
The following algorithm is applicable while deleting an element from the B+ Tree:
Firstly, we need to locate a leaf entry in the Tree that is holding the key and pointer. , delete
the leaf entry from the Tree if the Leaf fulfills the exact conditions of record deletion.
In case the leaf node only meets the satisfactory factor of being half full, then the operation
is completed; otherwise, the Leaf node has minimum entries and cannot be deleted.
The other linked nodes on the right and left can vacate any entries then move them to the
Leaf. If these criteria is not fulfilled, then they should combine the leaf node and its linked
node in the tree hierarchy.
Upon merging of leaf node with its neighbors on the right or left, entries of values in the leaf
node or linked neighbor pointing to the top-level node are deleted.
Summary:
B+ Tree is a self-balancing data structure for executing accurate and faster searching,
inserting and deleting procedures on data
We can easily retrieve complete data or partial data because going through the linked tree
structure makes it efficient.
The B+ tree structure grows and shrinks with an increase/decrease in the number of stored
records.
Storage of data on the leaf nodes and subsequent branching of internal nodes evidently
shortens the tree height, which reduces the disk input and output operations, ultimately
consuming much less space on the storage devices.
12.Explain the construction of expression tree with example. Give the applications of trees.
Expression Tree
The expression tree is a binary tree in which each internal node corresponds to the operator
and each leaf node corresponds to the operand so for example expression tree for 3 +
((5+9)*2) would be:

Evaluating the expression represented by an expression tree:


Let t be the expression tree
If t is not null then
If t.value is operand then
Return t.value
A = solve(t.left)
B = solve(t.right)
// calculate applies operator 't.value'
// on A and B, and returns value
Return calculate(A, B, t.value)
Construction of Expression Tree:
Now For constructing an expression tree we use a stack. We loop through input
expression and do the following for every character.
If a character is an operand push that into the stack
If a character is an operator pop two values from the stack make them its child and push
the current node again.
In the end, the only element of the stack will be the root of an expression tree.
13.Illustrate the construction of binomial heaps and its operations with a suitable example.
Binomial Heap:
A Binomial Heap is a set of Binomial Trees where each Binomial Tree follows Min Heap
property. And there can be at most one Binomial Tree of any degree.
Examples Binomial Heap:
12------------10--------------------20
/ \ / |\
15 50 70 50 40
| /| |
30 80 85 65
|
100
A Binomial Heap with 13 nodes. It is a collection of 3
Binomial Trees of orders 0, 2 and 3 from left to right.

10--------------------20
/ \ / |\
15 50 70 50 40
| /| |
30 80 85 65
|
100
A Binomial Heap with 12 nodes. It is a collection of 2
Binomial Trees of orders 2 and 3 from left to right.
Binary Representation of a number and Binomial Heaps
A Binomial Heap with n nodes has the number of Binomial Trees equal to the number of
set bits in the Binary representation of n. For example let n be 13, there 3 set bits in the
binary representation of n (00001101), hence 3 Binomial Trees. We can also relate the
degree of these Binomial Trees with positions of set bits. With this relation, we can
conclude that there are O(Logn) Binomial Trees in a Binomial Heap with ‘n’ nodes.
Operations of Binomial Heap:
The main operation in Binomial Heap is union(), all other operations mainly use this
operation. The union() operation is to combine two Binomial Heaps into one. Let us first
discuss other operations, we will discuss union later.
insert(H, k): Inserts a key ‘k’ to Binomial Heap ‘H’. This operation first creates a Binomial
Heap with single key ‘k’, then calls union on H and the new Binomial heap.
getMin(H): A simple way to getMin() is to traverse the list of root of Binomial Trees and
return the minimum key. This implementation requires O(Logn) time. It can be optimized to
O(1) by maintaining a pointer to minimum key root.
extractMin(H): This operation also uses union(). We first call getMin() to find the minimum
key Binomial Tree, then we remove the node and create a new Binomial Heap by
connecting all subtrees of the removed minimum node. Finally, we call union() on H and the
newly created Binomial Heap. This operation requires O(Logn) time.
delete(H): Like Binary Heap, delete operation first reduces the key to minus infinite, then
calls extractMin().
decreaseKey(H): decreaseKey() is also similar to Binary Heap. We compare the decreases
key with it parent and if parent’s key is more, we swap keys and recur for the parent. We
stop when we either reach a node whose parent has a smaller key or we hit the root node.
Time complexity of decreaseKey() is O(Logn).
Union operation in Binomial Heap:
Given two Binomial Heaps H1 and H2, union(H1, H2) creates a single Binomial Heap.
The first step is to simply merge the two Heaps in non-decreasing order of degrees. In the
following diagram, figure(b) shows the result after merging.
After the simple merge, we need to make sure that there is at most one Binomial Tree of
any order. To do this, we need to combine Binomial Trees of the same order. We traverse
the list of merged roots, we keep track of three-pointers, prev, x and next-x. There can be
following 4 cases when we traverse the list of roots.
—–Case 1: Orders of x and next-x are not same, we simply move ahead.
In following 3 cases orders of x and next-x are same.
—–Case 2: If the order of next-next-x is also same, move ahead.
—–Case 3: If the key of x is smaller than or equal to the key of next-x, then make next-x as
a child of x by linking it with x.
—–Case 4: If the key of x is greater, then make x as the child of next
14.i) Illustrate how the delete operation is performed on binary heap?
ii) Write suitable operations for percolate up and percolate down operations in a binary
heap.
Delete from a binary heap
This is the process of removing the highest priority value from the binary heap. The way
that the Heap is set up, the node with the highest priority is at the root. Finding it is easy
but the removal process must ensure that both the complete binary tree structure along
with the heap order property is maintained wo just removing the root would be a bad idea.
In order for the complete binary tree property to be maintained we will be removing the
right most node at the bottom level. Note that a complete binary tree with n nodes can
only have 1 shape, so the shape is pretty much determined by the fact that removing a
value creates a tree with one fewer node.
The empty spot that had been created by the removal of the value at root must be filled
and the value that had been in the rightmost node must go back into the heap. We can
accomplish this by doing the following:
If the value could be placed into the empty node (remember, this starts at root) without
violating the Heap Order Property, put it in and we are done
otherwise move the child with the higher priority up (the empty spot moves down).
Repeat until value is placed
The process of moving the empty spot down the heap is called percolate down
Illustrated example:

The heap property is repaired by comparing the added element with its parent and moving
the added element up a level (swapping positions with the parent). This process is called
"percolation up".
The heap property is repaired by comparing the added element with its parent and moving
the added element down a level (swapping positions with the parent). This process is called
"percolation down".
A binary heap is a complete binary tree which satisfies the heap ordering property. The
ordering can be one of two types:
the min-heap property: the value of each node is greater than or equal to the value of its
parent, with the minimum-value element at the root.
the max-heap property: the value of each node is less than or equal to the value of its parent,
with the maximum-value element at the root.
Throughout this chapter the word "heap" will always refer to a min-heap.

In a heap the highest (or lowest) priority element is always stored at the root, hence the
name "heap". A heap is not a sorted structure and can be regarded as partially ordered. As
you see from the picture, there is no particular relationship among nodes on any given level,
even among the siblings.
Since a heap is a complete binary tree, it has a smallest possible height - a heap with N
nodes always has O(log N) height.
A heap is useful data structure when you need to remove the object with the highest (or
lowest) priority. A common use of a heap is to implement a priority queue.
Insert
The new element is initially appended to the end of the heap (as the last element of the
array). The heap property is repaired by comparing the added element with its parent and
moving the added element up a level (swapping positions with the parent). This process is
called "percolation up". The comparison is repeated until the parent is larger than or equal to
the percolating element.

DeleteMin
The minimum element can be found at the root, which is the first element of the array. We
remove the root and replace it with the last element of the heap and then restore the heap
property by percolating down. Similar to insertion, the worst-case runtime is O{log n).
PART-C
i) Construct and evaluate a B tree of order 5 by inserting the following: 3, 14, 7, 1, 8, 5, 11, 17,
13, 6, 23, 12, 20, 26, 4, 16, 18, 24, 25 and 19. (10)
ii) Compare and assess B Tree and B+ Tree. (5)
ii)
i)Develop a routine for post order traversal. Is it possible to find minimum and maximum
value in the binary search tree using traversals? Discuss. (5)
ii)Display the given tree using Inorder, Preorder, Postorder traversals (6)

iii)Delete 11 and 10 from the above binary search tree and display the tree after each
deletion. (4)
Minimum value
Just traverse the node from root to left recursively until left is NULL. The node whose left is
NULL is the node with minimum value.
Maximum value
Traverse the node from root to right recursively until right is NULL. The node whose right is
NULL is the node with maximum value.
Ex.

Minimum value Example:


For the above tree, we start with 20, then we move left 8, we keep on moving to left until we
see NULL. Since left of 4 is NULL, 4 is the node with minimum value.
Maximum value Example:
Take the same tree, we start with same root 20, then we move right 22, Since right of 22 is
Null, 22 is the node with maximum value.

i) Draw B-Tree of order 5 for the keys {K, O, S, V, M, F, B, G, T, U, W} (5)


ii) Delete the keys K and G in order. (5)
iii) Justify the number of splits needed for inserts / delete with proper reasons. (5)
iii) There are 3 number of splits were happened during insertion.
->In step:5 Initially the tree was inserted with 4 keys.Here the maximum children is 5
because the order(m) is 5 so the maximum keys would be 4(m-1) when we insert M the
condition of binary search tree violates so the splitting takes place.
->In step:8 and step:11 the same problem occurs which was occured in step:5 so the splitting
takes place at the necessary positions.
In deletion no splitting were takes place.
Construct AVL tree for the followings after rotation.
-x-x-x-x-x-

You might also like