8. Trees

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 75

A tree is also one of the data structures that represent hierarchical data.

Suppose we want to
show the employees and their positions in the hierarchical form then it can be represented as
shown below:
This particular logical structure is known as a Tree.
Its structure is similar to the real tree, so it is
named a Tree. In this structure, the root is at the
top, and its branches are moving in a downward
direction. Therefore, we can say that the Tree data
structure is an efficient way of storing the data in a
hierarchical way.
Let's understand some key points of the Tree data structure.

• A tree data structure is defined as a collection of objects or entities


known as nodes that are linked together to represent or simulate
hierarchy.

• A tree data structure is a non-linear data structure because it does


not store in a sequential manner. It is a hierarchical structure as
elements in a Tree are arranged in multiple levels.

• In the Tree data structure, the topmost node is known as a root node.
Each node contains some data, and data can be of any type. In the
above tree structure, the node contains the name of the employee, so
the type of data would be a string.

• Each node contains some data and the link or reference of other
nodes that can be called children.
Some basic terms used in Tree data
•structure.
Root: The root node is the topmost node in the tree hierarchy. In other
words, the root node is the one that doesn't have any parent. In the above
structure, node numbered 1 is the root node of the tree. If a node is
directly linked to some other node, it would be called a parent-child
relationship.

• Child node: If the node is a descendant of any node, then the node is
known as a child node.

• Parent: If the node contains any sub-node, then that node is said to be the
parent of that sub-node.

• Sibling: The nodes that have the same parent are known as siblings.

• Leaf Node:- The node of the tree, which doesn't have any child node, is
called a leaf node. A leaf node is the bottom-most node of the tree. There
can be any number of leaf nodes present in a general tree. Leaf nodes can
also be called external nodes.

• Internal nodes: A node has atleast one child node known as an internal

• Ancestor node:- An ancestor of a node is any predecessor node on a path


from the root to that node. The root node doesn't have any ancestors. In
the tree shown in the above image, nodes 1, 2, and 5 are the ancestors of
node 10.

• Descendant: The immediate successor of the given node is known as a


descendant of a node. In the above figure, 10 is the descendant of node 5.
Properties of Tree data structure

• Recursive data structure: The tree is also known as a recursive data structure. A tree can
be defined as recursively because the distinguished node in a tree data structure is known as
a root node. Recursion means reducing something in a self-similar manner. So, this recursive
property of the tree data structure is implemented in various applications.

• Number of edges: If there are n nodes, then there would n-1 edges. Each arrow in the
structure represents the link or path. Each node, except the root node, will have atleast one
incoming link known as an edge. There would be one link for the parent-child relationship.

• Depth of node x: The depth of node x can be defined as the length of the path from the root
to the node x. One edge contributes one-unit length in the path. So, the depth of node x can
also be defined as the number of edges between the root node and the node x. The root node
has 0 depth.

• Height of node x: The height of node x can be defined as the longest path from the node x to
the leaf node.
Implementation of Tree
The tree data structure can be created by creating the nodes dynamically with the help of the
pointers. The tree in the memory can be represented as shown below:
In the above structure, the node contains three fields.
The second field stores the data; the first field stores the
address of the left child, and the third field stores the
address of the right child.
In programming, the structure of a node can be defined
as:

struct node
{
int data;
struct node *left;
struct node *right;
}
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.

Properties of Binary Tree

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

• 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.

• The minimum number of nodes possible at height h is


equal to h+1.

• 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.
Representation of a Binary tree
In order to represent a tree in a single one-dimensional array, the nodes are numbered sequentially level by left to right.

When the data of the tree is stored in an array

0 1 2 3 4 5 6 7

7 A B C D /0 E F
Location number zero of the array can be used to store the size of the tree of the total number
of nodes ( existing or not existing).
All non- existing nodes are represented by /0 in array.
Index of the left child of a node i=2*I 2n+1
Index of the right child of a node i=2*i+1 2n+2
Index of the parent node i=i/2 floor(n-1)/2

Sibling of a node I will be found at the location i + 1 , if I is a left child of its parents.
Similarly, if i is a right child of its parents then its sibling will be found at i - 1.
Types of Binary Tree
There are four types of Binary tree:
• Full/ proper/ strict Binary tree
• Complete Binary tree
• Perfect Binary tree
• Degenerate Binary tree
• Balanced Binary tree
Full/ proper/ strict Binary
The full binary tree istree
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.

Properties of Full Binary Tree


• 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.
• The maximum number of nodes is the same as
the number of nodes in the binary tree, i.e.,
2h+1 -1.
• The minimum number of nodes in the full binary
tree is 2*h-1.
• The minimum height of the full binary tree
is log2(n+1) - 1.
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.

Properties of Complete Binary Tree


• The maximum number of nodes in complete
binary tree is 2h+1 - 1.
• The minimum number of nodes in complete
binary tree is 2h.
• The minimum height of a complete binary tree
is log2(n+1) - 1.
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.

Note: All the perfect binary trees are the complete


binary trees as well as the full binary tree, but vice
versa is not true, i.e., all complete binary trees and
full binary trees are the perfect binary trees.
Degenerate Binary Tree
The degenerate binary tree is a tree in which all the internal nodes have only one children.
Balanced Binary Tree
The balanced binary tree is a tree in which both the left and right trees differ by atmost 1. For
example, AVL and Red-Black trees are balanced binary tree.
The process of visiting the nodes is known as tree traversal. There are three types traversals
used to visit a node:
• Inorder traversal
• Preorder traversal
• Postorder traversal
Preorder traversal
This technique follows the 'root left right' policy. It means that, first root node is visited after that
the left subtree is traversed recursively, and finally, right subtree is recursively traversed. As the
root node is traversed before (or pre) the left and right subtree, it is called preorder traversal.

The applications of preorder traversal include -


• It is used to create a copy of the tree.
• It can also be used to get the prefix expression of an expression tree.

Until all nodes of the tree are not visited

Step 1 - Visit the root node


Step 2 - Traverse the left subtree recursively.
Step 3 - Traverse the right subtree recursively.
Postorder traversal
This technique follows the 'left-right root' policy. It means that the first left subtree of the root node
is traversed, after that recursively traverses the right subtree, and finally, the root node is
traversed. As the root node is traversed after (or post) the left and right subtree, it is called
postorder traversal.

The applications of postorder traversal include –


• It is used to delete the tree.
• It can also be used to get the postfix expression of an expression tree.

Until all nodes of the tree are not visited

Step 1 - Traverse the left subtree recursively.


Step 2 - Traverse the right subtree recursively.
Step 3 - Visit the root node.
Inorder traversal
This technique follows the 'left root right' policy. It means that first left subtree is visited after that
root node is traversed, and finally, the right subtree is traversed. As the root node is traversed
between the left and right subtree, it is named inorder traversal.

The applications of Inorder traversal includes -


• It is used to get the BST nodes in increasing order.
• It can also be used to get the prefix expression of an expression tree.

Until all nodes of the tree are not visited

Step 1 - Traverse the left subtree recursively.


Step 2 - Visit the root node.
Step 3 - Traverse the right subtree recursively.
#include <stdio.h>
#include <stdlib.h>

struct node {
int element;
struct node* left;
struct node* right;
};

/*To create a new node*/


struct node* createNode(int val)
{
struct node* Node = (struct node*)malloc(sizeof(struct nod
e));
Node->element = val;
Node->left = NULL;
Node->right = NULL;

return (Node);
}

/*function to traverse the nodes of binary tree in preorder*/


void traversePreorder(struct node* root)
{
if (root == NULL)
return;
printf(" %d ", root->element);
traversePreorder(root->left);
traversePreorder(root->right);
}
/*function to traverse the nodes of binary tree in Inorder*/
void traverseInorder(struct node* root)
{
if (root == NULL)
return;
traverseInorder(root->left);
printf(" %d ", root->element);
traverseInorder(root->right);
}

/*function to traverse the nodes of binary tree in postorder*/


void traversePostorder(struct node* root)
{
if (root == NULL)
return;
traversePostorder(root->left);
traversePostorder(root->right);
printf(" %d ", root->element);
}
int main()
{
struct node* root = createNode(36);
root->left = createNode(26);
root->right = createNode(46);
root->left->left = createNode(21);
root->left->right = createNode(31);
root->left->left->left = createNode(11);
root->left->left->right = createNode(24);
root->right->left = createNode(41);
root->right->right = createNode(56);
root->right->right->left = createNode(51);
root->right->right->right = createNode(66);

printf("\n The Preorder traversal of given binary tree is -\n");


traversePreorder(root);

printf("\n The Inorder traversal of given binary tree is -\n");


traverseInorder(root);

printf("\n The Postorder traversal of given binary tree is -\n");


traversePostorder(root);

return 0;
}
2022-23

2019-20
A binary search tree follows some order to arrange the elements. In a Binary search tree, the
value of left node must be smaller than the parent node, and the value of right node must be
greater than the parent node. This rule is applied recursively to the left and right subtrees of the
root.

Advantages of Binary search tree


• Searching an element in the Binary search tree is easy as we always have a hint that which
subtree has the desired element.
• As compared to array and linked lists, insertion and deletion operations are faster in BST.
Suppose the data elements are - 45, 15, 79, 90, 10, 55, 12, 20, 50
Searching in Binary search tree
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.

Search (root, item)


Step 1 - if (item = root → data) or (root = NULL)
return root
else if (item < root → data)
return Search(root → left, item)
else
return Search(root → right, item)
END if
Step 2 - END
Deletion in Binary Search tree
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 -
• The node to be deleted is the leaf node, or,
• The node to be deleted has only one child, and,
• The node to be deleted has two children

When the node to be deleted is the leaf node


When the node to be deleted has only one child
In this case, we have to replace the target 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.
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 -
• First, find the inorder successor of the node to be deleted.
• After that, replace that node with the inorder successor until the target node is placed at the
leaf of tree.
• 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.
Huffman Coding Tree

Huffman coding is a technique of compressing data to reduce its size without losing any of the details. It was first
developed by David Huffman.
Huffman coding generally useful to compress the data in which there are frequently occurring character.

Suppose the sing below is to be sent over a network.


B C A A D D D C C A C A C A C

Calculate the frequency of each character in the string


1 6 5 3
B C A D
Sort the characters in increasing order of the frequency
1 3 5 6
B D A C
15

6 9

5
4
A

1 3

B D
AVL Tree is invented by GM Adelson - Velsky and EM Landis in 1962. The tree is named AVL in
honour of its inventors.
AVL Tree can be defined as height balanced binary search tree in which each node is associated
with a balance factor which is calculated by subtracting the height of its right sub-tree from that
of its left sub-tree.
Tree is said to be balanced if balance factor of each node is in between -1 to 1, otherwise, the
tree will be unbalanced and need to be balanced.

Balance Factor (k) = height (left(k)) - height (right(k))


If balance factor of any node is 1, it means that the left sub-tree is one level higher than the right
sub-tree.

If balance factor of any node is 0, it means that the left sub-tree and right sub-tree contain equal
height.

If balance factor of any node is -1, it means that the left sub-tree is one level lower than the right
sub-tree.
We perform rotation in AVL tree only in case if Balance Factor is other than -1, 0, and 1. There
are basically four types of rotations which are as follows:

1. L L rotation: Inserted node is in the left subtree of left subtree of A


2. R R rotation : Inserted node is in the right subtree of right subtree of A
3. L R rotation : Inserted node is in the right subtree of left subtree of A
4. R L rotation : Inserted node is in the left subtree of right subtree of A
Construct an AVL tree having the following elements H, I, J, B, A, E, C, F, D, G, K, L
Construct an AVL tree having the following elements H, I, J, B, A, E, C, F, D, G, K, L
Construct an AVL tree having the following elements H, I, J, B, A, E, C, F, D, G, K, L
Construct an AVL tree having the following elements H, I, J, B, A, E, C, F, D, G, K, L
Construct an AVL tree having the following elements H, I, J, B, A, E, C, F, D, G, K, L
B
Tree
B Tree is a specialized m-way tree that can be widely used for disk access.
A B-Tree of order m can have at most m-1 keys and m children.
One of the main reason of using B tree is its capability to store large number of keys in a single
node and large key values by keeping the height of the tree relatively small.

A B tree of order m contains all the properties of an M way tree. In addition, it contains the
following properties.

1. Every node in a B-Tree contains at most m children.


2. Every node in a B-Tree except the root node and the leaf node contain at least m/2 children.
3. The root nodes must have at least 2 nodes.
4. All leaf nodes must be at the same level.

It is not necessary that, all the nodes contain the same number of children but, each node must
have m/2 number of nodes.
A B tree of order 4 is shown in the following image.

Operations

Searching :
Searching in B Trees is similar to that in Binary search tree.
For example, if we search for an item 49 in the following B Tree. The process will something like
following :
1. Compare item 49 with root node 78. since 49 < 78 hence, move to its left sub-tree.
2. Since, 40<49<56, traverse right sub-tree of 40.
3. 49>45, move to right. Compare 49.
4. match found, return.

Searching in a B tree depends upon the height of the tree. The search algorithm takes O(log n)
time to search any element in a B tree.
Inserting
Insertions are done at the leaf node level.
The following algorithm needs to be followed in order to insert an item into B Tree.

1. Traverse the B Tree in order to find the appropriate leaf node at which the node can be inserted.
2. If the leaf node contain less than m-1 keys then insert the element in the increasing order.
3. Else, if the leaf node contains m-1 keys, then follow the following steps.
• Insert the new element in the increasing order of elements.
• Split the node into the two nodes at the median.
• Push the median element upto its parent node.
• If the parent node also contain m-1 number of keys, then split it too by following the same
steps.
Example:- Create a B Tree for the Fallowing Sequence F, S, Q, K, C, L, H, T, V, W, M, R, N, P, A, B Having a order - 5
Example:- Create a B Tree for the Fallowing Sequence F, S, Q, K, C, L, H, T, V, W, M, R, N, P, A, B Having a order - 5
Example:- Create a B Tree for the Fallowing Sequence F, S, Q, K, C, L, H, T, V, W, M, R, N, P, A, B Having a order - 5
Example:- Create a B Tree for the Fallowing Sequence F, S, Q, K, C, L, H, T, V, W, M, R, N, P, A, B Having a order - 5
Example:- Create a B Tree for the Fallowing Sequence F, S, Q, K, C, L, H, T, V, W, M, R, N, P, A, B Having a order - 5
Deletion

Deletion is also performed at the leaf nodes. The node which is to be deleted can either be a leaf
node or an internal node. Following algorithm needs to be followed in order to delete a node from a
B tree.

1. Locate the leaf node.


2. If there are more than m/2 keys in the leaf node then delete the desired key from the node.
3. If the leaf node doesn't contain m/2 keys then complete the keys by taking the element from
eight or left sibling.
• If the left sibling contains more than m/2 elements then push its largest element up to its
parent and move the intervening element down to the node where the key is deleted.
• If the right sibling contains more than m/2 elements then push its smallest element up to the
parent and move intervening element down to the node where the key is deleted.
4. If neither of the sibling contain more than m/2 elements then create a new leaf node by joining
two leaf nodes and the intervening element of the parent node.
5. If parent is left with less than m/2 nodes then, apply the above process on the parent too.

If the the node which is to be deleted is an internal node, then replace the node with its in-order
successor or predecessor. Since, successor or predecessor will always be on the leaf node hence, the
process will be similar as the node is being deleted from the leaf node.
50 80

10 20 60 70 75 90 95

81 82 89 92 93 10 11 11
0 0 1

4 5 6 14 15 16 23 27 51 52 64 65 68 72 73 77 78 79
50 80

10 20 60 70 75 90 95

77 78 79 72 73 77 78 79

4 5 6 14 15 16 23 27 51 52 65 68 72 73 77 78 79
50 80

10 20 60 70 75 90 95

77 78 79 72 73 77 78 79

4 5 6 14 15 16 23 27 51 52 65 68 72 73 77 78 79
50 80

10 16 60 70 75 90 95

77 78 79 72 73 77 78 79

4 5 6 14 15 20 27 51 52 65 68 72 73 77 78 79
50 80

10 16 60 70 77 90 95

77 78 79 72 73 77 78 79

4 5 6 14 15 20 27 51 52 65 68 73 75 78 79
50 80

10 16 70 77 90 95

77 78 79 72 73 77 78 79

4 5 6 14 15 20 27 51 52 60 68 73 75 78 79
Heap Data Structure
What is Heap?
A heap is a complete binary tree, and the binary tree is a tree in which the node can have utmost
two children. Before knowing more about the heap data structure, we should know about the
complete binary tree.

What is a complete binary tree?


A complete binary tree is a binary tree in which all the levels except the last level, i.e., leaf node
should be completely filled, and all the nodes should be left-justified.
How can we arrange the nodes in the Tree?
There are two types of the heap:
•Min Heap
•Max heap
Min Heap: The value of the parent node should be less than or equal to either of its children.
Or
In other words, the min-heap can be defined as, for every node i, the value of node i is greater
than or equal to its parent value except the root node. Mathematically, it can be defined as:
A[Parent(i)] <= A[i]
Max Heap: The value of the parent node is greater than or equal to its children.
Or
In other words, the max heap can be defined as for every node i; the value of node i is less than or
equal to its parent value except the root node. Mathematically, it can be defined as:
A[Parent(i)] >= A[i]
// algorithm to insert an element in the max heap.

insertHeap(A, n, value)
{
n=n+1; // n is incremented to insert the new element
A[n]=value; // assign new value at the nth position
i = n; // assign the value of n to i
// loop will be executed until i becomes 1.
while(i>1)
{
parent= floor value of i/2; // Calculating the floor value of i/2
// Condition to check whether the value of parent is less than the given node or not
if(A[parent]<A[i])
{
swap(A[parent], A[i]);
i = parent;
}
else
{
return;
}
}
}

Insertion in the Heap tree


44, 33, 77, 11, 55, 88, 66

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