Heap Flashcards
What is heap ?
A Heap is a Tree-based data structure, which satisfies the below properties:
1- A Heap is a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible).
2- A Heap is either Min Heap or Max Heap. In a Min-Heap, the key at root must be minimum among all keys present in the Binary Heap. The same property must be recursively true for all nodes in the Tree. Max Heap is similar to MinHeap.
What is binary heap ?
A Binary Heap is a heap where each node can have at most two children. In other words, a Binary Heap is a complete Binary Tree satisfying the above-mentioned properties.
example of min heap s
Example of max heap ?
How to represent binary heap ?
Since a Binary Heap is a complete Binary Tree, it can be easily represented using Arrays.
what is the index of root of binary heap is ?
0
which index returns the parent of the heap
Arr[(i-1)/2] Returns the parent node
which index returns the left child node ?
Arr[(2*i)+1] Returns the left child node
which index returns the right child node ?
Arr[(2*i)+2] Returns the right child node
How to get the max element in a max heap. approach only
Getting Maximum Element: In a Max-Heap, the maximum element is always present at the root node which is the first element in the array used to represent the Heap. So, the maximum element from a max heap can be simply obtained by returning the root node as Arr[0] in O(1) time complexity.
How to get the min element in a min heap. approach only
Getting Minimum Element: In a Min-Heap, the minimum element is always present at the root node which is the first element in the array used to represent the Heap. So, the minimum element from a minheap can be simply obtained by returning the root node as Arr[0] in O(1) time complexity.
what do you mean by Heapifying an Element
Generally, on inserting a new element onto a Heap, it does not satisfy the property of Heap as stated above on its own. The process of placing the element at the correct location so that it satisfies the Heap property is known as Heapify.
How to heapify a heap into a max heap ? approach only
Heapifying in a Max Heap: The property of Max Heap says that every node’s value must be greater than the values of its children nodes. So, to heapify a particular node swap the value of the node with the maximum value of its children nodes and continue the process until all of the nodes below it satisfies the Heap property.
What is the time complexity to heapify a tree ?
Time Complexity: The time complexity to heapify a single node is O(h), where h is equal to log(N) in a complete binary tree where N is the total number of nodes.
What is extract min in min heap ?
it means deleting or returning the root of the tree in a min heap