0% found this document useful (0 votes)
10 views33 pages

Week 12

The document provides an overview of Binary Search Trees (BST) and Binary Heaps, detailing their properties, operations, and implementations. It explains the structure of a BST, including searching, insertion, deletion, and traversal methods, as well as the characteristics of Min and Max Heaps, including heap operations and priority queue implementations. Additionally, it outlines the time complexities associated with various operations in both data structures.

Uploaded by

vaxshgadd
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)
10 views33 pages

Week 12

The document provides an overview of Binary Search Trees (BST) and Binary Heaps, detailing their properties, operations, and implementations. It explains the structure of a BST, including searching, insertion, deletion, and traversal methods, as well as the characteristics of Min and Max Heaps, including heap operations and priority queue implementations. Additionally, it outlines the time complexities associated with various operations in both data structures.

Uploaded by

vaxshgadd
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/ 33

DATA STRUCTURES

CSO102
WEEK-12 (DRAFT)
BINARY SEARCH TREE:

binary tree with 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.
BINARY SEARCH TREE:
BINARY SEARCH TREE: Node Structure

struct Node {
int key;
struct Node *left_child;
struct Node *right_child;
};
BINARY SEARCH TREE: Operations

1. Searching
2. Insertion
3. Deletion
4. Traversal

The traversal operation is of three different types:

1. Pre-order traversal: It will traverse the root first, then the left child
and at last the right child.

2. Post-order traversal: It will traverse the left subtree first, then root
and then the right subtree.

3. Inorder traversal: It will traverse the left subtree, then root and then
the right subtree.
BINARY SEARCH TREE: Operations

1. Searching
2. Insertion
3. Deletion
4. Traversal

The traversal operation is of three different types:

1. Pre-order traversal: It will traverse the root first, then the left child
and at last the right child.

2. Post-order traversal: It will traverse the left subtree first, then root
and then the right subtree.

3. Inorder traversal: It will traverse the left subtree, then root and then
the right subtree.
BINARY SEARCH TREE: Searching

if (root == NULL)
return NULL;
if (num == root->key)
return root->key;
if (num < root->key)
return Binary_search(root->left)
if (num > root->key)
return Binary_search(root->right)
BINARY SEARCH TREE: Insertion

if (Node == NULL)
return create_node(key)
if (key < Node->key)
Node->left_child = insert(Node->left_child, key);
else if (key > Node->key)
Node->right_child = insert(Node->right_child, key);
return Node;
BINARY SEARCH TREE: Deletion
Case 1: Deletion of a leaf node
Case 2: Deletion of an internal node having one child
Case 3: Deletion of an internal node having two child
nodes
BINARY SEARCH TREE: Sorting
1. Construct BST
2. Print inorder traversal sequence

Time Complexity: ?
BINARY HEAP
A Binary Heap is a Complete Binary Tree/ Almost Complete
Binary Tree which is used to store data efficiently to get the
max or min element based on its structure.

A Binary Heap is of two types:

Min Heap

Max Heap

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.

Max Binary Heap is similar to MinHeap.


MIN HEAP
MIN HEAP

Current Node: arr[i]


Parent Node: arr[|_i/2_|]
Left Child: arr[(2*i) ]
Right Child: arr[(2*i )+1]
MIN HEAP
MIN_HEAPIFY():
Suppose there exists a Node at some index i, where the
Minheap property is Violated.
We assume that all the subtrees of the tree rooted at
index i are valid binary heaps.
The Heapify function is used to restore the Minheap, by fixing
the violation.

STEPS
1. First find out the Minimum among the Violated Node, left,
and right child of Violated Node.
2. If the Minimum among them is the left child, then swap the
Violated Node value with the Left child value and recursively
call the function on the left Child.
3. If the Minimum among them is the right child, then swap
the Violated Node value with the right child value and
recursively call the function right Child.
4. Recursive call stops when the heap property is not
violated.
MIN_HEAPIFY( ):
void heapify(int arr[], int i)
{
int smallest = i; // The node which will be heapified
int l = 2 * i ; // left child node
int r = 2 * i + 1; // right child node
// Check if left child is smaller than its parent
if (l <= n && arr[l] < arr[smallest])
smallest = l;
// Check if right child is smaller than smallest
if (r < =n && arr[r] < arr[smallest])
smallest = r;
// If smallest is not parent
if (smallest != i) {
swap(arr[i], arr[smallest]);

// Recursively heapify the affected sub-tree


heapify(arr, smallest);
}
}
MIN_BUILD_HEAP

void buildHeap(int arr[])


{
// Perform level order traversal
// from last non-leaf node and heapify each node
for (int i = n/2; i >= 1; i--) {
heapify(arr, i);
}
}
HEAP SORT

1. Build a max heap from the input data.

2. At this point, the maximum element is stored at the root of the heap.
Replace it with the last item of the heap followed by reducing the size of the heap by 1.
Finally, heapify the root of the tree.

3. Repeat step 2 while the size of the heap is greater than 1.


HEAP SORT
HEAP SORT
HEAP SORT
void heapSort(int arr[], int N)
{

// Build max heap


for (int i = N / 2 - 1; i >= 1; i--)

heapify(arr, N, i);

// Heap sort
for (int i = N - 1; i >= 1; i--) {

swap(&arr[0], &arr[i]);

// Heapify root element to get highest element at


// root again
heapify(arr, i, 1);
}
}
MIN HEAP OPERATIONS
getMin()

extractMin()

decreaseKey()

insert()

delete()
MIN HEAP OPERATIONS
getMin(): It returns the root element of Min Heap. The time Complexity of this operation
is O(1). In case of a maxheap it would be getMax().
MIN HEAP OPERATIONS

extractMin(): Removes the minimum element from MinHeap. The time Complexity of
this Operation is O(log N) as this operation needs to maintain the heap property (by
calling heapify()) after removing the root.
MIN HEAP OPERATIONS

decreaseKey(): Decreases the value of the key. The time complexity of this operation is
O(log N). If the decreased key value of a node is greater than the parent of the node,
then we don’t need to do anything. Otherwise, we need to traverse up to fix the violated
heap property.
MIN HEAP OPERATIONS

insert(): Inserting a new key takes O(log N) time. We add a new key at the end of the
tree. If the new key is greater than its parent, then we don’t need to do anything.
Otherwise, we need to traverse up to fix the violated heap property.
MIN HEAP OPERATIONS

delete(): Deleting a key also takes O(log N) time. We replace the key to be deleted with
the minimum infinite by calling decreaseKey(). After decreaseKey(), the minus infinite
value must reach root, so we call extractMin() to remove the key.
Priority queue implementation using heap:

Naive Approach:

Suppose we have N elements and we have to insert these elements in the priority
queue. We can use list and can insert elements in O(N) time and can sort them to
maintain a priority queue in O(N logN ) time.
Priority queue implementation using heap:

Efficient Approach:
We can use heaps to implement the priority queue. It will take O(log N) time to insert and
delete each element in the priority queue.

Based on heap structure, priority queue also has two types max- priority queue and min -
priority queue.

Let’s focus on Max Priority Queue.

Max Priority Queue is based on the structure of max heap and can perform following
operations:

maximum(Arr) : It returns maximum element from the Arr.


extract_maximum (Arr) : It removes and return the maximum element from the Arr.
increase_val (Arr, i , val) : It increases the key of element stored at index i in Arr to new
value val.
insert_val (Arr, val ) : It inserts the element with value val in Arr.
Priority queue implementation using heap:

Maximum :

int maximum(int Arr[ ])


{
return Arr[ 1 ]; //as the maximum element is the root element in the max heap.
}
Priority queue implementation using heap:

Extract_Maximum :

int extract_maximum (int Arr[ ])


{
if(length == 0)
{
cout<< “Can’t remove element as queue is empty”;
return -1;
}
int max = Arr[1];
Arr[1] = Arr[length];
length = length -1;
max_heapify(Arr, 1);
return max;
}
Priority queue implementation using heap:

Increase Value :

void increase_value (int Arr[ ], int i, int val)


{
if(val < Arr[ i ])
{
cout<<”New value is less than current value, can’t be inserted” <<endl;
return;
}
Arr[ i ] = val;
while( i > 1 and Arr[ i/2 ] < Arr[ i ])
{
swap|(Arr[ i/2 ], Arr[ i ]);
i = i/2;
}
}
Priority queue implementation using heap:

Insert Value :

void insert_value (int Arr[ ], int val)


{
length = length + 1;
Arr[ length ] = -1; //assuming all the numbers greater than 0 are to be inserted in
queue.
increase_val (Arr, length, val);
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy