0% found this document useful (0 votes)
73 views16 pages

ADSA Unit-4

A priority queue is a special type of queue where each element has an associated priority and elements are served according to their priority, with higher priority elements being served first. A priority queue can be implemented using a binary heap stored in an array. Key operations on a priority queue implemented with a binary heap include insertion, extraction of highest priority element, and decreasing an element's priority. A binary search tree is a node-based binary tree where all left descendants of a node are less than or equal to the node and all right descendants are greater than or equal.

Uploaded by

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

ADSA Unit-4

A priority queue is a special type of queue where each element has an associated priority and elements are served according to their priority, with higher priority elements being served first. A priority queue can be implemented using a binary heap stored in an array. Key operations on a priority queue implemented with a binary heap include insertion, extraction of highest priority element, and decreasing an element's priority. A binary search tree is a node-based binary tree where all left descendants of a node are less than or equal to the node and all right descendants are greater than or equal.

Uploaded by

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

Priority queues

Definition:

A priority queue is a special type of queue in which each element is associated with a
priority value. And, elements are served on the basis of their priority. That is, higher priority
elements are served first. However, if elements with the same priority occur, they are served
according to their order in the queue.

ADT:

Priority Queue is an Abstract Data Type (ADT) that holds a collection of elements,


it is similar to a normal Queue, the difference is that the elements will be dequeued following
a priority order.

The Priority Queue interface can be implemented in different ways, is important to have

operations to add an element to the queue and to remove an element from the queue.
# Main operations
enqueue(value, priority) -> Enqueue an element
dequeue() -> Dequeue an element
peek() -> Check the element on the top
isEmpty() -> Check if the queue is empty

Since abstract data types don’t specify an implementation, this means it’s also incorrect to talk
about the time complexity of a given abstract data type.

Priority Queue Using Heaps:

s an extension of the queue with the following properties:  


1. Every item has a priority associated with it.
2. An element with high priority is dequeued before an element with low priority.
3. If two elements have the same priority, they are served according to their order in the
queue.
A Binary Heap is a Binary Tree with the following properties:  
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with
the DSA Self Paced Course at a student-friendly price and become industry ready.  To
complete your preparation from learning a language to DS Algo and many more,  please
refer Complete Interview Preparation Course .
In case you wish to attend live classes with experts, please refer DSA Live Classes for
Working Professionals  and Competitive Programming Live for Students .
1. It is a Complete Tree. This property of Binary Heap makes them suitable to be stored in
an array.
2. A Binary Heap is either Min Heap or Max Heap.
3. In a Min Binary Heap, the key at the root must be minimum among all keys present in
Binary Heap. The same property must be recursively true for all nodes in Binary Tree.
4. Similarly, in a Max Binary Heap, the key at the root must be maximum among all keys
present in Binary Heap. The same property must be recursively true for all nodes in
Binary Tree.
Operation on Binary Heap  
 insert(p): Inserts a new element with priority p.
 extractMax(): Extracts an element with maximum priority.
 remove(i): Removes an element pointed by an iterator i.
 getMax(): Returns an element with maximum priority.
 changePriority(i, p): Changes the priority of an element pointed by i to p.
Example of A Binary Max Heap  
 Suppose below is the given Binary Heap that follows all the properties of Binary Max
Heap. 
 

 Now a node with value  32 need to be insert in the above heap:  To insert an element,
attach the new element to any leaf. For Example A node with priority 32 can be added
to the leaf of the node 11. But this violates the heap property. To maintain the heap
property, shift up the new node 32. 
 

 Shift Up Operation get node with 32 at the correct position:  Swap the incorrectly
placed node with its parent until the heap property is satisfied. For Example: As
node 11 is less than node 32 so, swap node 11 and node 32. Then, swap node 14 and
node 32. And at last, swap node 31 and node 32. 
 
 ExtractMax: The maximum value is stored at the root of the tree. But the root of the
tree cannot be directly removed. First, it is replaced with any one of the leaves and then
removed. For Example: To remove Node 45, it is first replaced with node 11. But this
violates the heap property, so move the replaced node down. For that, use shift down
operation. 
 

 ShiftDown operation:  Swap the incorrectly placed node with a larger child until the
heap property is satisfied. For Example: Node 11 is swapped with node 32 then, with
node 31 and in last it is swapped with node 14. 
 

 ChangePriority:  Let the changed element shift up or down depending on whether its
priority decreased or increased. For Example: Change the priority of nodes 11 to 35,
due to this change the node has to shift up the node in order to maintain the heap
property.
 Remove: To remove an element, change its priority to a value larger than the current
maximum, then shift it up, and then extract it using extract max. Find the current
maximum using getMax.
 GetMax: The max value is stored at the root of the tree. To getmax, just return the
value at the root of the tree.
Array Representation of Binary Heap
Since the heap is maintained in form of a complete binary tree, because of this fact the
heap can be represented in the form of an array. To keep the tree complete and shallow,
while inserting a new element insert it in the leftmost vacant position in the last level i.e., at
the end of our array. Similarly, while extracting maximum replace the root with the last leaf
at the last level i.e., the last element of the array. Below is the illustration of the same:  
 

Binary Search Tree is a node-based binary tree data structure which has the following
properties:
 The left subtree of a node contains only nodes with keys lesser than the node’s key.
 The right subtree of a node contains only nodes with keys greater than the node’s key.
 The left and right subtree each must also be a binary search tree.

he properties that separate a binary search tree from a regular binary tree is

1. All nodes of left subtree are less than the root node
2. All nodes of right subtree are more than the root node
3. Both subtrees of each node are also BSTs i.e. they have the above two properties
Tree Traversals (Inorder, Preorder and Postorder)
 Difficulty Level : Easy
 Last Updated : 30 Nov, 2021
Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one
logical way to traverse them, trees can be traversed in different ways. Following are the
generally used ways for traversing trees.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with
the DSA Self Paced Course at a student-friendly price and become industry ready.  To
complete your preparation from learning a language to DS Algo and many more,  please
refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for
Working Professionals and Competitive Programming Live for Students.
Depth First Traversals: 
(a) Inorder (Left, Root, Right) : 4 2 5 1 3 
(b) Preorder (Root, Left, Right) : 1 2 4 5 3 
(c) Postorder (Left, Right, Root) : 4 5 2 3 1
Breadth-First or Level Order Traversal: 1 2 3 4 5 
Please see this post for Breadth-First Traversal.

Inorder Traversal (Practice): 


Algorithm Inorder(tree)
1. Traverse the left subtree, i.e., call Inorder(left-subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right-subtree)
Uses of Inorder 
In the case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing
order. To get nodes of BST in non-increasing order, a variation of Inorder traversal where
Inorder traversal s reversed can be used. 
Example: In order traversal for the above-given figure is 4 2 5 1 3.
Preorder Traversal (Practice): 
Algorithm Preorder(tree)
1. Visit the root.
2. Traverse the left subtree, i.e., call Preorder(left-subtree)
3. Traverse the right subtree, i.e., call Preorder(right-subtree)
Uses of Preorder 
Preorder traversal is used to create a copy of the tree. Preorder traversal is also used to get
prefix expression on an expression tree. Please
see http://en.wikipedia.org/wiki/Polish_notation know why prefix expressions are useful. 
Example: Preorder traversal for the above-given figure is 1 2 4 5 3.
Postorder Traversal (Practice): 
Algorithm Postorder(tree)
1. Traverse the left subtree, i.e., call Postorder(left-subtree)
2. Traverse the right subtree, i.e., call Postorder(right-subtree)
3. Visit the root.
Uses of Postorder 
Postorder traversal is used to delete the tree. Please see the question for the deletion of a
tree for details. Postorder traversal is also useful to get the postfix expression of an expression
tree. Please see http://en.wikipedia.org/wiki/Reverse_Polish_notation for the usage of postfix
expression.
Example: Postorder traversal for the above-given figure is 4 5 2 3 1.
4.

Binary search tree ADT


 Binary search tree is a binary tree in which every node X in the tree, the values
of all the keys in its left sub tree are smaller than the key value in X, and the
values of all the keys in its right sub tree are larger than the key vale in X.

 
typedef struct tree_node *tree_ptr; struct tree_node
 {
 element_type element;
 tree_ptr left; tree_ptr right;
};
 typedef tree_ptr TREE;

Example: 

43, 10, 79, 90, 12, 54, 11, 9, 50

Insert 43 into the tree as the root of the tree.

1. Read the next element, if it is lesser than the root node element, insert it as the root of
the left sub-tree.
2. Otherwise, insert it as the root of the right of the right sub-tree.

The process of creating BST by using the given elements, is shown in the image below.
Search Operation

The algorithm depends on the property of BST that if each left subtree has values below root
and each right subtree has values above the root.

If the value is below the root, we can say for sure that the value is not in the right subtree; we
need to only search in the left subtree and if the value is above the root, we can say for sure
that the value is not in the left subtree; we need to only search in the right subtree.

 tem == root.val: We terminate the search as the item is found


 item > root.val: We just check the right subtree because all the values in the left
subtree are lesser than root.val
 item < root.val: Now we just check the left subtree as all values in the right subtree
are greater than root.val
 Algorithm:

If root == NULL
return NULL;
If number == root->data
return root->data;
If number < root->data
return search(root->left)
If number > root->data
return search(root->right)
.

Let us try to visualize this with a diagram

4 is not found so, traverse through the right subtree of 3


4 is not found so, traverse through the left subtree of 6

4 is found

If the value is found, we return the value so that it gets propagated in each recursion step as
shown in the image below.

If you might have noticed, we have called return search(struct node*) four times. When we
return either the new node or NULL, the value gets returned again and again until
search(root) returns the final result.

If the value is found in any of the subtrees, it is propagated up so that in the end it is returned, otherwise
null is returned

If the value is not found, we eventually reach the left or right child of a leaf node which is
NULL and it gets propagated and returned.
Insert Operation

Inserting a value in the correct position is similar to searching because we try to


maintain the rule that the left subtree is lesser than root and the right subtree is
larger than root.

We keep going to either right subtree or left subtree depending on the value and
when we reach a point left or right subtree is null, we put the new node there.

1. f the root is NULL, create a new node with value item and return it.
2. Else, Compare item with root.val

 If root.val < item, recurse for right subtree


 If root.val > item, recurse for left subtree

Algorithm:

If node == NULL
return createNode(data)
if (data < node->data)
node->left = insert(node->left, data);
else if (data > node->data)
node->right = insert(node->right, data);
return node;

The algorithm isn't as simple as it looks. Let's try to visualize how we add a number to an
existing BST.
4<8 so, transverse through the left child of 8

4>3 so, transverse through the right child of 8

4<6 so, transverse through the left child of 6

Insert 4 as a left child of 6

We have attached the node but we still have to exit from the function without doing any
damage to the rest of the tree. This is where the return node; at the end comes in handy. In
the case of NULL, the newly created node is returned and attached to the parent node,
otherwise the same node is returned without any change as we go up until we return to the
root.
Deletion Operation

There are three cases for deleting a node from a binary search tree.

1. Check if the root is NULL, if it is, just return the root itself. It's an empty tree!
2. If root.val < item, recurse the right subtree.
3. If root.val > item, recurse the left subtree.
4. If both above conditions above false, this means root.val == item.
5. Now we first need to check how many child did root have.
6. CASE 1: No Child → Just delete root or deallocate space occupied by it
7. CASE 2: One Child →Replace root by its child
8. CASE 3: Two Children

 Find the inorder successor of the root (Its the smallest element of its right subtree).
Let's call it new_root.
 Replace root by its inorder successor
 Now recurse to the right subtree and delete new_root.
9. Return the root.

Case 1

In the first case, the node to be deleted is the leaf node. In such a case, simply delete the node
from the tree.

4 is to be deleted
Delete the node

Case II

In the second case, the node to be deleted lies has a single child node. In such a case follow the steps
below:

1. Replace that node with its child node.


2. Remove the child node from its original position.

6 is to be deleted

copy the value of its child to the node and delete the child
Final tree

Case III

In the third case, the node to be deleted has two children. In such a case follow the steps
below:

1. Get the inorder successor of that node.

2. Replace the node with the inorder successor.

3. Remove the inorder successor from its original position.

3 is to be deleted

Copy the value of the inorder successor (4) to the node


Delete the inorder successor

You might also like