0% found this document useful (0 votes)
3 views

Tree Notes

DSA tree
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Tree Notes

DSA tree
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

lOMoARcPSD|13574892

Data Structures

TREES INTRODUCTION

The tree is a nonlinear hierarchical data structure and comprises a collection of entities known as
nodes. It connects each node in the tree data structure using "edges”, both directed and
undirected.

The image below represents the tree data structure. The blue-colored circles depict the nodes of
the tree and the black lines connecting each node with another are called edges.

You will understand the parts of trees better, in the terminologies section.

The Necessity for a Tree in Data Structures

Other data structures like arrays, linked-list, stacks, and queues are linear data structures, and all
these data structures store data in sequential order. Time complexity increases with increasing
data size to perform operations like insertion and deletion on these linear data structures. But it is
not acceptable for today's world of computation.

The non-linear structure of trees enhances the data storing, data accessing, and manipulation
processes by employing advanced control methods traversal through it. You will learn about tree
traversal in the upcoming section.

Tree Terminologies

The following are some of the basic tree terms

• Root Node
• Edge
• Parent node
• Child node

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

• Siblings
• Leaf nodes or external nodes
• Internal nodes
• Degree
• Level
• Height
• Depth
• Path
• Subtree

Root

• In a tree data structure, the root is the first node of the tree. The root node is the initial
node of the tree in data structures.

• In the tree data structure, there must be only one root node.

Edge

• In a tree in data structures, the connecting link of any two nodes is called the edge of the
tree data structure.

• In the tree data structure, N number of nodes connecting with N -1 number of edges.

Parent

In the tree in data structures, the node that is the predecessor of any node is known as a parent
node, or a node with a branch from itself to any other successive node is called the parent node.

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

Child

• The node, a descendant of any node, is known as child nodes in data structures.

• In a tree, any number of parent nodes can have any number of child nodes.

• In a tree, every node except the root node is a child node.

Siblings

In trees in the data structure, nodes that belong to the same parent are called siblings.

Leaf

• Trees in the data structure, the node with no child, is known as a leaf node.

• In trees, leaf nodes are also called external nodes or terminal nodes.

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

Internal nodes

• Trees in the data structure have at least one child node known as internal nodes.

• In trees, nodes other than leaf nodes are internal nodes.

• Sometimes root nodes are also called internal nodes if the tree has more than one node.

Degree

• In the tree data structure, the total number of children of a node is called the degree of
the node.

• The highest degree of the node among all the nodes in a tree is called the Degree of Tree.

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

Level

In tree data structures, the root node is said to be at level 0, and the root node's children are at
level 1, and the children of that node at level 1 will be level 2, and so on.

Height

• In a tree data structure, the number of edges from the leaf node to the particular node in
the longest path is known as the height of that node.

• In the tree, the height of the root node is called "Height of Tree".

• The tree height of all leaf nodes is 0.

Depth

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

• In a tree, many edges from the root node to the particular node are called the depth of the
tree.

• In the tree, the total number of edges from the root node to the leaf node in the longest
path is known as "Depth of Tree".

• In the tree data structures, the depth of the root node is 0.

Path

• In the tree in data structures, the sequence of nodes and edges from one node to another
node is called the path between those two nodes.

• The length of a path is the total number of nodes in a path.zx

Subtree

In the tree in data structures, each child from a node shapes a sub-tree recursively and every child
in the tree will form a sub-tree on its parent node.

General Tree

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

The general tree is the type of tree where there are no constraints on the hierarchical structure.

Properties

• The general tree follows all properties of the tree data structure.

• A node can have any number of nodes.

BINARY TREES

The Binary tree means that the node can have maximum two children. Here, binary name itself
suggests that 'two'; therefore, each node can have either 0, 1 or 2 children.

Let's understand the binary tree through an example.

The above tree is a binary tree because each node contains the utmost two children. The logical
representation of the above tree is given below:

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

In the above tree, node 1 contains two pointers, i.e., left and a right pointer pointing to the left
and right node respectively. The node 2 contains both the nodes (left and right node); therefore, it
has two pointers (left and right). The nodes 3, 5 and 6 are the leaf nodes, so all these nodes
contain NULL pointer on both left and right parts.

Properties of Binary Tree

o At each level of i, the maximum number of nodes is 2i.

o The height of the tree is defined as the longest path from the root node to the leaf node.
The tree which is shown above has a height equal to 3. Therefore, the maximum number
of nodes at height 3 is equal to (1+2+4+8) = 15. In general, the maximum number of
nodes possible at height h is (20 + 21 + 22+….2h) = 2h+1 -1.

o If the number of nodes is minimum, then the height of the tree would be maximum.
Conversely, if the number of nodes is maximum, then the height of the tree would be
minimum.

If there are 'n' number of nodes in the binary tree.

The minimum height can be computed as:

As we know that,

n = 2h+1 -1

n+1 = 2h+1

Taking log on both the sides,

log2(n+1) = log2(2h+1)

log2(n+1) = h+1

h = log2(n+1) – 1

The maximum height can be computed as:

As we know that,

n = h+1

h= n-1

Types of Binary Tree

There are four types of Binary tree:

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

o Full/ proper/ strict Binary tree

o Complete Binary tree

o Perfect Binary tree

o Degenerate Binary tree

o Balanced Binary tree

1. Full/ proper/ strict Binary tree

The full binary tree is also known as a strict binary tree. The tree can only be considered as the
full binary tree if each node must contain either 0 or 2 children. The full binary tree can also be
defined as the tree in which each node must contain 2 children except the leaf nodes.

Let's look at the simple example of the Full Binary tree.

In the above tree, we can observe that each node is either containing zero or two children;
therefore, it is a Full Binary tree.

Properties of Full Binary Tree

o The number of leaf nodes is equal to the number of internal nodes plus 1. In the above
example, the number of internal nodes is 5; therefore, the number of leaf nodes is equal to
6.

o The maximum number of nodes is the same as the number of nodes in the binary tree,
i.e., 2h+1 -1.

o The minimum number of nodes in the full binary tree is 2*h-1.

o The minimum height of the full binary tree is log2(n+1) - 1.

o The maximum height of the full binary tree can be computed as:

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

n= 2*h - 1

n+1 = 2*h

h = n+1/2

Complete Binary Tree

The complete binary tree is a tree in which all the nodes are completely filled except the last
level. In the last level, all the nodes must be as left as possible. In a complete binary tree, the
nodes should be added from the left.

Let's create a complete binary tree.

The above tree is a complete binary tree because all the nodes are completely filled, and all the
nodes in the last level are added at the left first.

Properties of Complete Binary Tree

o The maximum number of nodes in complete binary tree is 2h+1 - 1.

o The minimum number of nodes in complete binary tree is 2h.

o The minimum height of a complete binary tree is log2(n+1) - 1.

o The maximum height of a complete binary tree is

Perfect Binary Tree

A tree is a perfect binary tree if all the internal nodes have 2 children, and all the leaf nodes are at
the same level.

10

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

Let's look at a simple example of a perfect binary tree.

The below tree is not a perfect binary tree because all the leaf nodes are not at the same level.

Degenerate Binary Tree

The degenerate binary tree is a tree in which all the internal nodes have only one children.

Let's understand the Degenerate binary tree through examples.

The above tree is a degenerate binary tree because all the nodes have only one child. It is also
known as a right-skewed tree as all the nodes have a right child only.

11

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

The above tree is also a degenerate binary tree because all the nodes have only one child. It is
also known as a left-skewed tree as all the nodes have a left child only.

Balanced Binary Tree

The balanced binary tree is a tree in which both the left and right trees height differ by atmost 1.
For example, AVL and Red-Black trees are balanced binary tree.

Let's understand the balanced binary tree through examples.

The above tree is a balanced binary tree because the difference between the height of left subtree
and right subtree is zero.

The above tree is not a balanced binary tree because the difference between the height of left
subtree and the right subtree is greater than 1.

12

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

Tree Traversals
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.

Depth First Traversals:


(a) Inorder (Left, Root, Right)
(b) Preorder (Root, Left, Right)
(c) Postorder (Left, Right, Root)
Breadth-First or Level Order Traversal

Let see each traversal method with example.

Inorder Traversal

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

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)


13

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

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.

Example: Preorder traversal for the above-given figure is 1 2 4 5 3.

Postorder Traversal

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.

EXAMPLE

Example: Postorder traversal for the above-given figure is 4 5 2 3 1.

Uses of Postorder
Postorder traversal is also useful to get the postfix expression of an expression tree.

Level Order Binary Tree Traversal

Level order traversal of a tree is breadth first traversal for the tree.

Level order traversal of the above tree is 1 2 3 4 5

14

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

Construct a binary tree from inorder and postorder traversals

The idea is to start with the root node, which would be the last item in the postorder sequence,
and find the boundary of its left and right subtree in the inorder sequence. To find the boundary,
search for the index of the root node in the inorder sequence. All keys before the root node in the
inorder sequence become part of the left subtree, and all keys after the root node become part of
the right subtree. Repeat this recursively for all nodes in the tree and construct the tree in the
process.

To illustrate, consider the following inorder and postorder sequence:

Inorder : { 4, 2, 1, 7, 5, 8, 3, 6 }
Postorder : { 4, 2, 7, 8, 5, 6, 3, 1 }

Root would be the last element in the postorder sequence, i.e., 1. Next, locate the index of the
root node in the inorder sequence. Now since 1 is the root node, all nodes before 1 in the inorder
sequence must be included in the left subtree of the root node, i.e., {4, 2} and all the nodes
after 1 must be included in the right subtree, i.e., {7, 5, 8, 3, 6}. Now the problem is reduced to
building the left and right subtrees and linking them to the root node.

Left subtree:
Inorder : {4, 2}
Postorder : {4, 2}
Right subtree:
Inorder : {7, 5, 8, 3, 6}
Postorder : {7, 8, 5, 6, 3}

The idea is to recursively follow the above approach until the complete tree is constructed.

The final tree will be

15

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

Binary Search Tree(BST)


A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned
properties −

• The value of the key of the left sub-tree is less than the value of its parent (root) node's
key.

• The value of the key of the right sub-tree is greater than or equal to the value of its parent
(root) node's key.

let's understand the concept of Binary search tree with an example.

In the above figure, we can observe that the root node is 40, and all the nodes of the left subtree
are smaller than the root node, and all the nodes of the right subtree are greater than the root
node.

Similarly, we can see the left child of root node is greater than its left child and smaller than its
right child. So, it also satisfies the property of binary search tree. Therefore, we can say that the
tree in the above image is a binary search tree.

Suppose if we change the value of node 35 to 55 in the above tree, check whether the tree will be
binary search tree or not.

In the above tree, the value of root node is 40, which is greater than its left child 30 but smaller
than right child of 30, i.e., 55. So, the above tree does not satisfy the property of Binary search
tree. Therefore, the above tree is not a binary search tree.

16

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

Advantages of Binary search tree

o Searching an element in the Binary search tree is easy as we always have a hint that
which subtree has the desired element.

o As compared to array and linked lists, insertion and deletion operations are faster in BST.

Example of creating a Binary Search Tree (BST)

Now, let's see the creation of binary search tree using an example.

Suppose the data elements are - 45, 15, 79, 90, 10, 55, 12, 20, 50

o First, we have to insert 45 into the tree as the root of the tree.

o Then, read the next element; if it is smaller than the root node, insert it as the root of the
left subtree, and move to the next element.

o Otherwise, if the element is larger than the root node, then insert it as the root of the right
subtree.

Now, let's see the process of creating the Binary search tree using the given data element. The
process of creating the BST is shown below -

Step 1 - Insert 45.

Step 2 - Insert 15.

As 15 is smaller than 45, so insert it as the root node of the left subtree.

Step 3 - Insert 79.

As 79 is greater than 45, so insert it as the root node of the right subtree.

17

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

Step 4 - Insert 90.

90 is greater than 45 and 79, so it will be inserted as the right subtree of 79.

Step 5 - Insert 10.

10 is smaller than 45 and 15, so it will be inserted as a left subtree of 15.

Step 6 - Insert 55.

55 is larger than 45 and smaller than 79, so it will be inserted as the left subtree of 79.

Step 7 - Insert 12.

18

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

12 is smaller than 45 and 15 but greater than 10, so it will be inserted as the right subtree of 10.

Step 8 - Insert 20.

20 is smaller than 45 but greater than 15, so it will be inserted as the right subtree of 15.

Step 9 - Insert 50.

50 is greater than 45 but smaller than 79 and 55. So, it will be inserted as a left subtree of 55.

Now, the creation of binary search tree is completed. After that, let's move towards the
operations that can be performed on Binary search tree.

We can perform insert, delete and search operations on the binary search tree.

Let's understand how a search is performed on a binary search tree.

19

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

Searching in Binary search tree(BST)

Searching means to find or locate a specific element or node in a data structure. In Binary search
tree, searching a node is easy because elements in BST are stored in a specific order. The steps of
searching a node in Binary Search tree are listed as follows -

1. First, compare the element to be searched with the root element of the tree.

2. If root is matched with the target element, then return the node's location.

3. If it is not matched, then check whether the item is less than the root element, if it is
smaller than the root element, then move to the left subtree.

4. If it is larger than the root element, then move to the right subtree.

5. Repeat the above procedure recursively until the match is found.

6. If the element is not found or not present in the tree, then return NULL.

Now, let's understand the searching in binary tree using an example. We are taking the binary
search tree formed above. Suppose we have to find node 20 from the below tree.

Step1:

Step2:

20

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

Step3:

Now, let's see the algorithm to search an element in the Binary search tree.

Now let's understand how the deletion is performed on a binary search tree. We will also see an
example to delete an element from the given tree.

Deletion in Binary Search tree(BST)

In a binary search tree, we must delete a node from the tree by keeping in mind that the property
of BST is not violated. To delete a node from BST, there are three possible situations occur -

o The node to be deleted is the leaf node, or,

o The node to be deleted has only one child, and,

o The node to be deleted has two children

We will understand the situations listed above in detail.

When the node to be deleted is the leaf node

It is the simplest case to delete a node in BST. Here, we have to replace the leaf node with NULL
and simply free the allocated space.

21

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

We can see the process to delete a leaf node from BST in the below image. In below image,
suppose we have to delete node 90, as the node to be deleted is a leaf node, so it will be replaced
with NULL, and the allocated space will free.

When the node to be deleted has only one child

In this case, we have to replace the target node(Deleting node) with its child, and then delete the
child node. It means that after replacing the target node with its child node, the child node will
now contain the value to be deleted. So, we simply have to replace the child node with NULL
and free up the allocated space.

We can see the process of deleting a node with one child from BST in the below image.

In the below image, suppose we have to delete the node 79, as the node to be deleted has only
one child, so it will be replaced with its child 55.

So, the replaced node 79 will now be a leaf node that can be easily deleted.

When the node to be deleted has two children

This case of deleting a node in BST is a bit complex among other two cases. In such a case, the
steps to be followed are listed as follows -

o First, find the inorder successor of the node to be deleted.

22

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

o After that, replace that node with the inorder successor until the target node is placed at
the leaf of tree.

o And at last, replace the node with NULL and free up the allocated space.

The inorder successor is required when the right child of the node is not empty. We can obtain
the inorder successor by finding the minimum element in the right child of the node.

We can see the process of deleting a node with two children from BST in the below image. In the
below image, suppose we have to delete node 45 that is the root node, as the node to be deleted
has two children, so it will be replaced with its inorder successor. Now, node 45 will be at the
leaf of the tree so that it can be deleted easily.

Now let's understand how insertion is performed on a binary search tree.

Insertion in Binary Search tree(BST)

A new key in BST is always inserted at the leaf. To insert an element in BST, we have to start
searching from the root node; if the node to be inserted is less than the root node, then search for
an empty location in the left subtree. Else, search for the empty location in the right subtree and
insert the data. Insert in BST is similar to searching, as we always have to maintain the rule that
the left subtree is smaller than the root, and right subtree is larger than the root.

Now, let's see the process of inserting a node into BST using an example.

23

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

The complexity of the Binary Search tree

Let's see the time and space complexity of the Binary search tree. We will see the time
complexity for insertion, deletion, and searching operations in best case, average case, and worst
case.

1. Time Complexity

Operations Best case time Average case Worst case time


complexity time complexity complexity

Insertion O(log n) O(log n) O(n)

Deletion O(log n) O(log n) O(n)

Search O(log n) O(log n) O(n)

Worst case scenario indicates the BST is the Degenerated BST for all the operations (insertion,
deletion and search)

Where 'n' is the number of nodes in the given tree.

2. Space Complexity

Operations Space complexity

Insertion O(n)

Deletion O(n)

Search O(n)

24

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

o The space complexity of all operations of Binary search tree is O(n).

Implementation of binary Search Tree traversal method

Program:

#include <stdio.h>
#include <stdlib.h>
struct btnode
{
int value;
struct btnode *l;
struct btnode *r;
}*root = NULL, *temp = NULL, *t2, *t1;
void insert();
void create();
void search( struct btnode *root);
void inorder(struct btnode *t);
void preorder(struct btnode *t);
void postorder(struct btnode *t);
void main()
{
int ch;
printf("\nOPERATIONS ---");
printf("\n1 - Insert an element into tree\n");
printf("2 - Inorder Traversal\n");
printf("3 - Preorder Traversal\n");
printf("4 - Postorder Traversal\n");
printf("5 - Exit\n");
while(1)
{
printf("\nEnter your choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
insert();
break;
case 2:
inorder(root);
break;
case 3:
25

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

preorder(root);
break;
case 4:
postorder(root);
break;
case 5:
exit(0);
default :
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}
/* To insert a node in the tree */
void insert()
{
create();
if (root == NULL)
root = temp;
else
search(root);
}
/* To create a node */
void create()
{
int data;
printf("Enter data of node to be inserted : ");
scanf("%d", &data);
temp = (struct btnode *)malloc(1*sizeof(struct btnode));
temp->value = data;
temp->l = temp->r = NULL;
}
/* Function to search the appropriate position to insert the new node */
void search(struct btnode *t)
{
if ((temp->value > t->value) && (t->r != NULL)) /* value more than root node value insert
at right */
search(t->r);
else if ((temp->value > t->value) && (t->r == NULL))
t->r = temp;

26

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

else if ((temp->value < t->value) && (t->l != NULL)) /* value less than root node value
insert at left */
search(t->l);
else if ((temp->value < t->value) && (t->l == NULL))
t->l = temp;
}
/* recursive function to perform inorder traversal of tree */
void inorder(struct btnode *t)
{
if (root == NULL)
{
printf("No elements in a tree to display");
return;
}
if (t->l != NULL)
inorder(t->l);
printf("%d -> ", t->value);
if (t->r != NULL)
inorder(t->r);
}
/* To find the preorder traversal */
void preorder(struct btnode *t)
{
if (root == NULL)
{
printf("No elements in a tree to display");
return;
}
printf("%d -> ", t->value);
if (t->l != NULL)
preorder(t->l);
if (t->r != NULL)
preorder(t->r);
}
/* To find the postorder traversal */
void postorder(struct btnode *t)
{
if (root == NULL)
{
printf("No elements in a tree to display ");

27

Downloaded by Dr.Kishore Verma S ([email protected])


lOMoARcPSD|13574892

return;
}
if (t->l != NULL)
postorder(t->l);
if (t->r != NULL)
postorder(t->r);
printf("%d -> ", t->value);
}
OUTPUT:

28

Downloaded by Dr.Kishore Verma S ([email protected])


THREADED BINARY TREE

A binary tree is represented using array representation or linked list


representation. When a binary tree is represented using linked list representation, if any
node is not having a child we use NULL pointer in that position. In any binary tree linked
list representation, there are more number of NULL pointer than actual pointers.
Generally, in any binary tree linked list representation, if there are 2N number of
reference fields, then N+1 number of reference fields are filled with NULL ( N+1 are
NULL out of 2N ). This NULL pointer does not play any role except indicating there is
no link (no child).

A. J. Perlis and C. Thornton have proposed new binary tree called "Threaded Binary
Tree", which make use of NULL pointer to improve its traversal processes. In threaded
binary tree, NULL pointers are replaced by references to other nodes in the tree,
called threads.
A threaded binary tree defined as follows:
"A binary tree is threaded by making all right child pointers that would normally be null
point to the inorder successor of the node (if it exists), and all left child pointers that
would normally be null point to the inorder predecessor of the node."

Why do we need Threaded Binary Tree?


Binary trees have a lot of wasted space: the leaf nodes each have 2 null pointers. We can
use these pointers to help us in inorder traversals. Threaded binary tree makes the tree tra-
versal faster since we do not need stack or recursion for traversal.

Comparison between a normal binary tree and threaded binary tree

Types of threaded binary trees:


Single Threaded: each node is threaded towards either the in-order predecessor or succes-
sor (left or right) means all right null pointers will point to inorder successor OR all left
null pointers will point to inorder predecessor.
Double threaded: each node is threaded towards both the in-order predecessor and suc-
cessor (left and right) means all right null pointers will point to inorder succes-
sor AND all left null pointers will point to inorder predecessor.

Single Threaded: each node is threaded towards either the in-order predecessor or succes-
sor (left or right) means all right null pointers will point to inorder successor OR all left
null pointers will point to inorder predecessor.

Implementation:
Let’s see how the Node structure will look like
The binary tree can have at most two children. But if the tree have only one
children, or no children, the link part in the linked list representation remains
null. In threaded binary tree representation, empty links are reused as threads.
Types are
1. Single threaded tree - (Left threaded and right threaded)
2. Fully threaded binary tree
Single Left threaded tree:
In this, if some node has no left child, then the left pointer will point to its
inorder predecessor. If no predecessor is present, then it will point to header
node.

Fig: Single Left threaded tree


Single Right threaded tree:
In this, if some node has no right child, then the right pointer will point to its
inorder successor. If no successor is present, then it will point to header node.
Fig: Single Right threaded tree

Fully threaded binary tree:


In fully threaded binary tree, each node has five fields. Three fields like normal
binary tree node, another two fields to store Boolean value to denote whether
link of that side is actual link or thread.

Left Thread Flag Left Link Data Right Link Right Thread Flag

Fig: Fully threaded binary tree


Heap

Heap data structure is a specialized binary tree-based data structure. In a heap


data structure, nodes are arranged based on their values. A heap data structure
also called as Binary Heap. There are two types of heap data structures.

1. Max Heap
2. Min Heap

Every heap data structure has the following properties...


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.

Min Heap
In a Min-Heap the key present at the root node must be minimum among the
keys present at all of it’s children. The same property must be recursively true
for all sub-trees in that Binary Tree.

Max Heap
In a Max-Heap the key present at the root node must be greatest among the
keys present at all of it’s children. The same property must be recursively true
for all sub-trees in that Binary Tree.
Operations on Max Heap
The following operations are performed on a Max heap data structure.

1. Finding Maximum
2. Insertion
3. Deletion

Finding Maximum Value Operation in Max Heap


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.

Insertion Operation in Min Heap


Note : The procedure to create Max Heap is similar but consider max values
instead of max values.
Algorithm for max heap
Inserting one element at a time, with the following steps,
Step 1 − Create a new node at the end of heap.
Step 2 − Assign new value to the node.
Step 3 − Compare the value of this child node with its parent.
Step 4 − If value of parent is greater than child, then swap them.
Step 5 − Repeat step 3 & 4 until Heap property holds.

Insert into a heap the following values in order: 10,6,20,5, 16, 17, 13,2
We will use smaller values has higher priority as our priority ordering.
insert 10:

insert 6:

insert 20:

insert 5:
insert 16:
insert 17:

Repeat the steps for 13 and 2. The final tree is

Delete from a binary heap


This is the process of removing the highest priority value from the binary heap.
The deleting an element must ensure
• complete binary tree structure
• heap order property
is maintained after the removal of an element.
Deletion Procedure

• Replace the root or element to be deleted by the last element.


• Delete the last element from the Heap.
• Since, the last element is now placed at the position of the root node. So,
it may not follow the heap property. Therefore, heapify the last node
placed at the position of root.
The process of moving the empty spot down the heap is called percolate down.
Applications of Heap

1) Heap Sort: Heap Sort uses Binary Heap to sort an array in O(nLogn) time.

2) Priority Queue: Priority queues can be efficiently implemented using Binary


Heap because it supports insert(), delete() and extractmax(), decreaseKey()
operations in O(logn) time. Binomoial Heap and Fibonacci Heap are variations
of Binary Heap. These variations perform union also efficiently.

3) Graph Algorithms: The priority queues are especially used in Graph


Algorithms like Dijkstra’s Shortest Path and Prim’s Minimum Spanning Tree.

4) Many problems can be efficiently solved using Heaps. See following for
example.

a) K’th Largest Element in an array.


b) Sort an almost sorted array
c ) Merge K Sorted Arrays.

You might also like