CHAPTER 8 - TREESds
CHAPTER 8 - TREESds
CHAPTER 8 - TREESds
TREES
TREE
A tree is a non-linear data structure which describes the hierarchical relationships between a
finite set of elements called nodes. One of the nodes is designated as root node while the
remaining set of nodes are grouped into subsets which itself is a tree. The hierarchical
relationships are described by referring to each subtree as a child of the root, while the root is
referred to as the parent of each tree.
Basic terminology
A tree consists of finite set of elements, called nodes, and a finite set of directed lines
called branches, that connect the nodes.
The number of branches associated with a node is the degree of the node.
When the branch is directed away from the node, it is an out-degree branch.
The sum of the in-degree and out-degree branches is the degree of the node.
If the tree is not empty, the first node is called the root.
All nodes in the tree can have zero, one, or more branches leaving them; that is, they
may have out-degree of zero, one, or more.
A leaf is any node with an out-degree of zero, that is, a node with no successors.
A node is a parent if it has successor nodes; that is, if it has out-degree greater than
zero.
Two or more nodes with the same parents are called siblings.
An ancestor is any node in the path from the root to the node.
A descendant is any node in the path below the parent node; that is, all nodes in the
paths from a given node to a leaf are descendants of that node.
A path is a sequence of nodes in which each node is adjacent to the next node.
The level of a node is its distance from the root. The root is at level 0, its children are
at level 1, etc.
The height of the tree is the level of the leaf in the longest path from the root plus 1.
By definition the height of any empty tree is -1.
A sub-tree is any connected structure below the root. The first node in the sub-tree is
known is the root of the sub-tree.
Example:
1) Given that we need to store N nodes in a binary tree, the maximum height is H max N
3) Given a height of the binary tree, H, the minimum number of nodes in the tree is given as
follows: N
min H
4) Given a height of the binary tree, H, the maximum number of nodes in the tree is given as
max 2 1
follows: N H
5) The children of any node in a tree can be accessed by following only one branch path, the one
that leads to the desired node.
6) The nodes at level 1, which are children of the root, can be accessed by following only one
branch; the nodes of level 2 of a tree can be accessed by following only two branches from the
root, etc.
A complete tree has the maximum number of entries for its height. The maximum
number is reached when the last level is full.
A tree is considered nearly complete if it has the minimum height for its nodes and all
nodes in the last level are found on the left.
2) Connect Siblings
Method:
In order to insert a new element into a Binary tree we need to search for the leaf node in either of
sub-trees and then we insert the element as the next element to the leaf node in either of the trees.
1) if(tree==NULL)
if[(A[2*I]=NULL)
A[2*I]= Item;
else
if[(A[2*I+1]=NULL)
A[2*I+1]= Item; }}
Method:
In order to delete an element from a Binary tree we need to search for the leaf node in either of
sub-trees and then we delete the element the leaf node in either of the sub-trees.
1) if(tree==NULL)
if[(A[2*I]=NULL)
// Delete element
A[2*I]= NULL;
else
if[(A[2*I+1]=NULL)
// Delete element
A[2*I+1]= NULL;
}
Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 7
4) Binary tree Traversals
A traversal is a process that visits all the nodes in the tree. Since a tree is a nonlinear data
structure, there is no unique traversal. The traversal algorithms are grouped in the following two
kinds:
Pre-order traversal
In-order traversal
Post-order traversal
Method:
1) if (tree != NULL)
Preorder(tree[left], data);
Preorder(tree[right], data);
In-order traversal
Method:
1) if (tree != NULL)
Inorder(tree[left], data);
Print: tree[data];
Inorder(tree[right], data);
Post-order traversal
Method:
1) if (tree != NULL)
Postorder(tree[left], data);
Postorder(tree[right], data);
Print: tree[data];
// This algorithm dynamically allocates memory for a node and creates the head structure for the
tree.
// Local declarations
int data;
if(TREECOUNT=0)
tree = (TREE*tree)malloc(sizeof(TREE*tree);
tree->data = data;
tree->left = NULL;
4) return(tree);
1) if(tree==NULL)
tree= Pnew;
tree->data = data;
tree->left = NULL;
else
2) if(tree->left=NULL)
else
3) if(tree->right=NULL)
4) (TREECOUNT )++;
5) return(tree);
1) if(tree!=NULL)
2) if(tree->left!=NULL)&& if(tree->right!=NULL)
if(tree->left!=NULL)
tree->left = NULL;
else
3) if(tree->right!=NULL)
tree->right = NULL;
4) (TREECOUNT)--;
5) return(tree);
1) if (tree != NULL)
Preorder(treeleft, data);
Preorder(treeright, data);
5) return(tree);
1) if (tree != NULL)
Inorder(treeright, data);
5) return(tree);
1) if (tree != NULL)
Postorder(treeleft, data);
Postorder(treeright, data);
5) return(tree); }
Pre-order: 50, 25, 12, 37, 30, 40, 75, 62,60, 70, 87
Post-order: 12, 30, 40, 37, 25, 60, 70, 62, 87, 75, 50
Solution:
1. The first element in the pre-order traversal is the root of the tree. So, here 50 will be the root of
the tree.
2. We will find the index of element next to 50 i.e. 25 in the post-order traversal. The index
found is 4. Let this index is denoted by 'pos'.
3. All the elements to the left of this index and element at this index (i.e. from 0 to 4 index) will
be in the left sub-tree of 50.
4. And all the elements to the right of this index (from 6 to 10) will be in the right sub-tree of 50.
Now the structure of tree is:
Problem 3:
In-order Traversal: 4, 2, 1, 7, 5, 8, 3, 6
Post-order Traversal: 4, 2, 7, 8, 5, 6, 3, 1
Solution:
2) Next locate the index of the root node in the in-order sequence.
4) Now the problem is reduced to building left and right sub-trees and linking them to the root
node.
Number of distinct Binary trees possible with n labeled nodes is (2n!) / (n+1)!
If the nodes are similar (unlabeled), then the no. of distinct binary trees will be the above value
divided by the no. of distinct permutations possible for a binary tree structure, which will be n!
for a tree with n nodes.
The Catalan numbers form a sequence of natural numbers that occur in various counting
problems.
1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845,
35357670, 129644790, 477638700, 1767263190, 6564120420, 24466267020, 91482563640,
343059613650, 1289904147324, 4861946401452, ...
1) Binary Search Tree: Used in many search applications that constantly shows and hides data,
such as data. For example, map and set objects in many libraries.
2) Binary Space Partition: Used in almost any 3D video game to determine which objects need
to be rendered.
3) Binary Tries: Used in almost every high-bandwidth router to store router tables.
5) Hash Trees: Used in P2P programs and special image signatures that require a hash to be
validated, but the entire file is not available.
6) Heaps: Used to implement efficient priority queues and also used in heap sort.
7) Treap: Randomized data structure for wireless networks and memory allocation.
8) T-Tree: Although most databases use a form of B-tree to store data on the drive, databases
that store all (most) data often use T-trees.
9) Huffman Coding Tree (Chip Uni): Used in compression algorithms, eg. For example, in
.jpeg and .mp3.GGM Trees file formats - used in cryptographic applications to generate a tree
with pseudo-random numbers.
A binary search tree (BST) is a binary tree with the following properties:
All items in the left sub-tree are less than the root.
All items in the right sub-tree are greater than or equal to the root.
Each sub-tree is itself a binary search tree.
Example:
Inserting a new element into the Binary Search Tree using Arrays
Inserting data into a binary search tree is much simpler. All we need to do is follow the branches
to an empty sub-tree and then insert the new node. All BST insertions take place at a leaf or a
leaf like node that is a node that has only one null sub-tree.
BSTInsertion
1) If (tree!== null)
tree[left]=insertBST[item, tree[left]);
else
tree[right]=insertBST[item, tree[right]);
Return 1;
} // end of insertBST
To delete a node from a binary search tree, we must first locate it. There are four possible cases
when we delete a node.
Find the largest node in the deleted node’s left sub-tree and move its data to
replace the deleted node’s data or
Find the smallest node in the deleted node’s right sub-tree and move its data to
replace the deleted node’s data.
1) If (tree == null)
Return 0;
2) If (item< tree[value])
tree[left]=deleteBST (root[left],item);
else
3) If (item> tree[value])
tree[right]=deleteBST (root[right],item);
else
temp= FindMin(root[right]);
tree[value] = tempvalue;
free(temp);
Return 1;
else
temp=tree;
6) if(tree[left]==NULL) then
tree = tree[right];
else
7) if(tree[right]==NULL) then
tree = tree[left];
free(temp);
void *element;
typedef struct
int count;
NODE * root;
}BST_TREE;
// This algorithm dynamically allocates memory for a node and creates the head structure for the
tree.
// Local declarations
int data;
if(TREECOUNT=0)
tree = (TREE*tree)malloc(sizeof(TREE*tree)
tree->data = data;
tree->left = NULL;
4) return(tree); }
1) If (root == null)
root = Pnew;
else
2) current = root;
parent = current;
current = currentleft;
else
else
7) parentright = Pnew;
8) (TREECOUNT)++;
Return(tree);
} // end of insertBST
Deleting a node from the Binary Search Tree using Linked lists
1) If (root == null)
Return 0;
else
temp= FindMin(rootright);
rootvalue = tempvalue;
free(temp);
Return 1;
else
temp=root;
6) if(rootleft==NULL) then
root = rootright;
else
7) if(rootright==NULL) then
root = rootleft;
free(temp);
9) return(root); }
An AVL tree is a Binary Search tree in which the heights of the sub-trees differ by no more than
one and every sub-tree is an AVL tree.
An AVL tree is a Height-balanced binary search tree. The balance factor for any node in an AVL
tree must be +1, 0, or -1.
The descriptive identifiers, LH for left high(+1) to indicate that the left sub-tree is higher than the
right sub-tree, EH for even high(0) to indicate that the sub-trees are the same height, and RH for
right high(-1) to indicate that the left sub-tree is shorter than the right sub-tree.
Balancing AVL trees is done by rotating nodes either to the left or to the right.
When the out of balance condition has been created by a right-high sub-tree of a right-high tree,
we must balance the tree by rotating the out-of-balance node to the left.
The first two cases required single rotations to balance the trees. In this case we need to rotate
two nodes, one to the left and one to the right, to balance the tree.
To balance the tree, we first rotate the right sub-tree and then rotate the root left. Because the
out-of-balance condition is created by a right-high sub-tree on a right-high branch, we must
double rotate. We begin by rotating the right sub-tree to the right, we then rotate the root left,
which gives us the balanced tree.
Whenever a new node is inserted into the AVL tree, an out of balance in heights will arise in
either of the sub-trees. We have to perform the rotations to balance the heights of the sub-trees.
1) if (tree== NULL)
tree[data] = X;
tree[left]=NULL;
tree[right]= NULL;
else
Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 42
2) if (X < tree[data])
if(Height(tree[Left]) – (Height(tree[Right]) == 2)
if (X < tree[data])
else
3) if (X > tree[data])
if(Height(treeLeft) – (Height(treeRight) == 2)
if (X > tree[data])
else
Position K1;
K1 = K2 [Left];
K2 [Left] = K2[Right];
K1[Right] = K2;
return K1;
Position K2;
K2 = K1[Right];
K1[Right] = K2[Left];
K2 [Left]= K1;
return K2;
To delete a node from an AVL list, we need to determine if it is a leaf or leaf like node. If a node
has two sub-trees, we must search for a Left sub-tree for its largest node. When we find it, we
move its data to replace the deleted data and then recursively call the delete function to delete a
valid leaf node.
We must search for a Right sub-tree for its smallest node. When we find it, we move its data to
replace the deleted data and then recursively call the delete function to delete a valid leaf node.
Delete Right balance is used when a delete has occurred on a left sub-tree and the tree needs to
be rebalanced. We need to rebalance only if the root is right-high.
Delete Left balance is used when a delete has occurred on a right sub-tree and the tree needs to
be rebalanced. We need to rebalance only if the root is left high.
In this case we see an out-of-balance tree in which the root is left high and the left sub-tree is
right high. To balance this tree, we first rotate the left sub-tree to the left, and then we rotate the
root to the right making the left node the new root (right-of-left).
1) if (tree!= NULL)
if (X < tree[data])
if(Height(tree[Left]) – (Height(tree[Right]) == 2)
if (X < tree[data])
else
3) if (X > tree[data])
if(Height(tree[Left]) – (Height(tree[Right]) == 2)
if (X > tree[data])
else
Position K1;
K1 = K2 [Left];
K2 [Left] = K2[Right];
K1[Right] = K2;
return K1;
Position K2;
K2 = K1[Right];
K1[Right] = K2[Left];
K2 [Left]= K1;
return K2;
typedef struct {
int key;
int data;
int bal ;
}NODE;
int count;
NODE * root;
} AVL_ TREE;
Algorithm AVL_Create(tree)
AVL_TREE * tree
if (tree)
tree count = 0;
Return(tree); }
1) if (tree== NULL)
tree data = X;
tree Height = 0;
tree left=NULL;
else
if(Height(treeLeft) – (Height(treeRight) == 2)
else
if(Height(treeLeft) – (Height(treeRight) == 2)
else
5) (TREECOUNT)++;
return(tree);
Position K1;
K1 = K2 Left;
K2 Left = K2 Right;
K1 Right = K2;
return K1;
Position K2;
K2 = K1 Right;
K1 Right = K2 Left;
K2 Left= K1;
return K2;
1) if (tree!= NULL)
if(Height(treeLeft) – (Height(treeRight) == 2)
else
if(Height(treeLeft) – (Height(treeRight) == 2)
else
5) (TREECOUNT)--;
return(tree);
Position K1;
K1 = K2 Left;
K2 Left = K2 Right;
K1 Right = K2;
return K1; }
Position K2;
K2 = K1 Right;
K1 Right = K2 Left;
K2 Left= K1;
return K2;
The idea of threaded binary trees is to make in-order traversal faster and do it without stack and
without recursion. A binary tree is made threaded by making all right child pointers that would
normally be NULL point to the in-order successor of the node (if it exists).
Double Threaded: Where both left and right NULL pointers are made to point to in-order
predecessor and in-order successor respectively. The predecessor threads are useful for reverse
in-order traversal and post-order traversal. The threads are also useful for fast accessing
ancestors of a node.
{
1) if (n == NULL)
return NULL;
n = n->left;
return n;
}
In deletion, first the key to be deleted is searched, and then there are different cases for deleting
the Node in which key is found.
In BST, for deleting a leaf Node the left or right pointer of parent was set to NULL. Here instead
of setting the pointer to NULL it is made a thread.
If the leaf Node is to be deleted is left child of its parent then after deletion, left pointer of parent
should become a thread pointing to its predecessor of the parent Node after deletion.
struct Node *caseA(struct Node *root, struct Node *par, struct Node *ptr)
1) if (par == NULL)
root = NULL;
par->lthread = true;
par->left = ptr->left;
else
par->rthread = true;
par->right = ptr->right;
free(ptr);
return root;
After deleting the Node as in a BST, the in-order successor and in-order predecessor of the Node
are found out.
If Node to be deleted has left sub-tree, then after deletion right thread of its predecessor should
point to its successor.
If Node to be deleted has right sub-tree, then after deletion left thread of its successor should
point to its predecessor.
struct Node *caseB(struct Node *root, struct Node *par, struct Node *ptr)
if (ptr->lthread == false)
child = ptr->left;
else
child = ptr->right;
if (par == NULL)
root = child;
par->left = child;
else
par->right = child;
Node *s = inSucc(ptr);
Node *p = inPred(ptr);
p->right = s;
else
if (ptr->rthread == false)
s->left = p;
free(ptr);
return root;
We find in-order successor of Node ptr (Node to be deleted) and then copy the information of
this successor into Node ptr. After this in-order successor Node is deleted using either Case A or
Case B.
struct Node *caseC(struct Node *root, struct Node *par, struct Node *ptr)
parsucc = succ;
3) ptr->info = succ->info;
else
return root;
Forest
The forest is composed of several trees. The root node of each tree in the forest can be regarded
as a brother. Since each tree can be converted into a binary tree, the forest can also be converted
into a binary tree.
(2) The first binary tree does not move, starting from the second binary tree, and sequentially
taking the root node of the latter binary tree as the front The right child node of the root node of a
binary tree is connected with a line. The binary tree obtained when all the binary trees are
connected is the binary tree converted from the forest.
O = (T,O’)
Rotations
1. Draw the orchard so that the first child of each vertex is immediately below the vertex, rather
than centering the children below the vertex.
2. Draw a vertical link from each vertex to its first child and draw a horizontal link from each
vertex to its next sibling.
Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 72
3. Remove the remaining original links.
4. Rotate the diagram 450 clockwise so that the vertical links appear as left links and the
horizontal links as right links.
EXPRESSION TREES
• Infix traversal
• Postfix traversal
• Prefix traversal
Infix traversal
Algorithm Infix(tree)
4) Print (tree-token)
} // End if
} // End if
} // End of Infix
Postfix traversal
Algorithm Postfix(tree)
} // End of if
} // End of Postfix
Prefix traversal
Algorithm Prefix(tree)
} // End of if
} // End of Prefix
MULTIWAY TREES
A multi-way tree is defined as a tree that can have more than two children. If a multi-way tree
can have maximum m children, then this tree is called as multi-way tree of order m (or an m-way
tree).
The nodes in an m-way tree will be made up of m-1 key fields and pointers to children.
An m-way search tree is a m-way tree in which following condition should be satisfied:
2-3 TREES
A 2-3 tree is a search tree. However, it is very different from a binary search tree.
If the tree is empty, create a node and put value into the node.
Otherwise find the leaf node where the value belongs.
If the leaf node has only one value, put the new value into the node.
If the leaf node has more than two values, split the node and promote the median of the
three values to parent.
If the parent then has three values, continue to split and promote, forming a new root
node if necessary.
Base cases
If we reach the leaf-node and it doesn’t contain the required key value K, return False.
if K < currentNode.leftVal, we explore the left sub-tree of the current node.
else
else
B-Tree is a self-balanced search tree in which every node contains multiple keys and has more
than two children.
Here, the number of keys in a node and number of children for a node depends on the order of B-
Tree. Every B-Tree has an order m.
B-Tree Properties
Property 2: All nodes except root must have at least [m/2]-1 keys and maximum of m-1 keys.
Property 3: All non leaf nodes except root (i.e. all internal nodes) must have at least m/2
children.
Property 4: If the root node is a non leaf node, then it must have at least 2 children.
Property 5: A non leaf node with n-1 keys must have n number of children.
Example
B-Tree of Order 4 contains a maximum of 3 key values in a node and maximum of 4 children for
a node.
Search
Insertion
Deletion
The search operation in B-Tree is similar to the search operation in Binary Search Tree. In a
Binary search tree, the search process starts from the root node and we make a 2-way decision
every time (we go to either left subtree or right subtree). In B-Tree also search process starts
from the root node but here we make an n-way decision every time. Where 'n' is the total number
of children the node has. In a B-Tree, the search operation is performed with O(log n) time
complexity. The search operation is performed as follows...
Step 2: Compare the search element with first key value of root node in the tree.
Step 3: If both are matched, then display "Given node is found!!!" and terminate the function
Step 4: If both are not matched, then check whether search element is smaller or larger than that
key value.
Step 5: If search element is smaller, then continue the search process in left subtree.
Step 6: If search element is larger, then compare the search element with next key value in the
same node and repeat steps 3, 4, 5 and 6 until we find the exact match or until the search element
is compared with last key value in the leaf node.
Step 7: If the last key value in the leaf node is also not matched then display "Element is not
found" and terminate the function.
Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 87
Insertion Operation in B-Tree
In a B-Tree, a new element must be added only at the leaf node. That means, the new keyValue
is always attached to the leaf node only. The insertion operation is performed as follows:
Step 2: If tree is Empty, then create a new node with new key value and insert it into the tree as a
root node.
Step 3: If tree is Not Empty, then find the suitable leaf node to which the new key value is added
using Binary Search Tree logic.
Step 4: If that leaf node has empty position, add the new key value to that leaf node in ascending
order of key value within the node.
Step 5: If that leaf node is already full, split that leaf node by sending middle value to its parent
node. Repeat the same until the sending value is fixed into a node.
Step 6: If the splitting is performed at root node then the middle value becomes new root node
for the tree and the height of the tree is increased by one.
Example
Solution:
Deleting an element on a B-tree consists of three main events: searching the node where the key
to be deleted exists, deleting the key and balancing the tree if required.
While deleting a tree, a condition called underflow may occur. Underflow occurs when a node
contains less than the minimum number of keys it should hold.
Case I:
The key to be deleted lies in the leaf. There are two cases for it.
1. The deletion of the key does not violate the property of the minimum number of keys a node
should hold.
In the tree below, deleting 32 does not violate the above properties.
First, visit the immediate left sibling. If the left sibling node has more than a minimum number
of keys, then borrow a key from this node.
In the tree below, deleting 31 results in the above condition. Let us borrow a key from the left
sibling node.
If the key to be deleted lies in the internal node, the following cases occur.
The internal node, which is deleted, is replaced by an inorder predecessor if the left child has
more than the minimum number of keys.
3. If either child has exactly a minimum number of keys then, merge the left and the right
children.
Case III:
In this case, the height of the tree shrinks. If the target key lies in an internal node, and the
deletion of the key leads to a fewer number of keys in the node (i.e. less than the minimum
required), then look for the inorder predecessor and the inorder successor. If both the children
contain a minimum number of keys then, borrowing cannot take place. This leads to Case II(3)
i.e. merging the children.
Again, look for the sibling to borrow a key. But, if the sibling also has only a minimum number
of keys then, merge the node with the sibling along with the parent. Arrange the children
accordingly (increasing order).
B+ Trees
B+ Tree is an extension of B Tree which allows efficient insertion, deletion and search
operations.
In B Tree, Keys and records both can be stored in the internal as well as leaf nodes. Whereas, in
B+ tree, records (data) can only be stored on the leaf nodes while internal nodes can only store
the key values.
The leaf nodes of a B+ tree are linked together in the form of singly linked lists to make the
search queries more efficient.
B+ Tree are used to store the large amount of data which can not be stored in the main memory.
Due to the fact that, size of main memory is always limited, the internal nodes (keys to access
records) of the B+ tree are stored in the main memory whereas, leaf nodes are stored in the
secondary memory.
The internal nodes of B+ tree are often called index nodes. A B+ tree of order 3 is shown in the
following figure.
Insertion in B+ Tree
Step 2: If the leaf doesn't have required space, split the node and copy the middle node to the
next index node.
Step 3: If the index node doesn't have required space, split the node and copy the middle element
to the next index page.
Insert the value 195 into the B+ tree of order 5 shown in the following figure.
195 will be inserted in the right sub-tree of 120 after 190. Insert it at the desired position.
The node contains greater than the maximum number of elements i.e. 4, therefore split it and
place the median node up to the parent.
Deletion in B+ Tree
Step 2: if the leaf node contains less than minimum number of elements, merge down the node
with its sibling and delete the key in between them.
Step 3: if the index node contains less than minimum number of elements, merge the node with
the sibling and move down the key in between them.
Example
Delete the key 200 from the B+ Tree shown in the following figure.
200 is present in the right sub-tree of 190, after 195. Delete it.
Now, element 120 is the single element present in the node which is violating the B+ Tree
properties. Therefore, we need to merge it by using 60, 78, 108 and 120.
In a heap data structure, nodes are arranged based on their values. A heap data structure some-
times also called as Binary Heap.
There are two types of heap data structures and they are as follows:
Max Heap
Min Heap
Property #1 (Ordering): Nodes must be arranged in an order according to their values based on
Max heap or Min heap.
Property #2 (Structural): All levels in a heap must be full except the last level and all nodes must
be filled from left to right strictly.
BUILDING A HEAP
Max Heap
Min Heap
Max Heap
Max heap is a specialized full binary tree in which every parent node contains greater or equal
value than its child nodes.
Finding Maximum
Insertion
Deletion
Finding the node which has maximum value in a max heap is very simple.
In a max heap, the root node has the maximum value than all other nodes. So, directly we
can display root node value as the maximum value in max heap.
Step 3: If newNode value is greater than its parent, then swap both of them.
Step 4: Repeat step 2 and step 3 until newNode value is less than its parent node (or) newNode
reaches to root.
Example:
Consider the above max heap. Insert a new node with value 85.
Step 1: Insert the newNode with value 85 as last leaf from left to right. That means newNode is
added as a right child of node with value 75. After adding max heap is as follows.
Step 1: Swap the root node with last node in max heap.
Step 3: Now, compare root value with its left child value.
Step 4: If root value is smaller than its left child, then compare left child with its right sibling.
Else go to Step 6
Step 5: If left child value is larger than its right sibling, then swap root with left
child otherwise swap root with its right child.
Step 6: If root value is larger than its left child, then compare root value with its right
child value.
Step 7: If root value is smaller than its right child, then swap root with right child otherwise stop
the process.
Step 8: Repeat the same until root node fixes at its exact position.
Example
Consider the above max heap. Delete root node (90) from the max heap.
Step 1: Swap the root node (90) with last node 75 in max heap. After swapping max heap is as
follows.
Min-Heap is where the value of the root node is less than or equal to either of its children.
For Input → 35 33 42 10 14 19 27 44 26 31
INSERTION
Move the child up until you reach the root node and the heap property is satisfied.
Example
Example