Pds ch-3 Print
Pds ch-3 Print
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.
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.
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
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
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.
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.
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.
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.
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:
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.