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

DS UNIT 2 notes

Unit II covers the fundamentals of trees, including basic terminology, types of trees such as binary trees, and their representations using arrays and linked lists. It also discusses tree traversal methods (inorder, preorder, postorder) and introduces heaps, including min and max binary heaps. Additionally, the document explains the construction of expression trees for representing algebraic expressions.

Uploaded by

22eg510a06
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)
4 views

DS UNIT 2 notes

Unit II covers the fundamentals of trees, including basic terminology, types of trees such as binary trees, and their representations using arrays and linked lists. It also discusses tree traversal methods (inorder, preorder, postorder) and introduces heaps, including min and max binary heaps. Additionally, the document explains the construction of expression trees for representing algebraic expressions.

Uploaded by

22eg510a06
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/ 46

UNIT II

Unit II : Trees: Basic terminology,


Types of trees: Binary Tree: terminology, Complete and Full Binary Tree,
Extended Binary Trees, Threaded Binary Trees and In order Threading.
Representation of Trees using Arrays and Linked lists (advantages and
disadvantages).
Tree Traversal and Representation of Algebraic expressions;
Algorithms for Tree Traversals.
Heaps: Introduction, types of Heaps – Min binary heap, Max binary
heap.
Tree- Basic terminology
▪ In Linear Data Structure data is organized in sequential order and in non-
linear data structure data is organized in random order
▪ Tree is a non-linear data structure which organizes data in hierarchical
fashion.
▪ It is a collection of Nodes (vertices) and edges(links) which is organized in
hierarchical structure.
1) Root node

▪ The first node is called as Root


Node.
▪ Every tree must have a root node.
▪ In any tree, there must be only one
root node.

2) Edge
• The connecting link between any
two nodes is called as EDGE.
• A tree with n nodes will have n-1
edges
3.Parent node
▪ The node which is a predecessor
of any node is called as PARENT
NODE.
▪ Parent node can also be defined as
"The node which has child /
children".

4.Child node
▪ The node which is descendant of any
node is called as CHILD Node.
▪ i.e the node which has a link from its
parent node is called as child node.
▪ Any parent node can have any number of
child nodes.
5.Siblings
▪ Nodes which belong to same
Parent are called
as SIBLINGS

6.Leaf node
▪ The node which does not have a child is
called as LEAF Node
▪ Leaf node is also called as 'Terminal' node
or external node
7.Internal Nodes
▪ Nodes other than leaf nodes are called
as Internal Nodes.
▪ The root node is also said to be
Internal Node if the tree has more than
one node.
▪ Internal nodes are also called as 'Non-
Terminal' nodes.

8.Degree

▪ The total number of children of a node is


called as DEGREE of that Node.
▪ The highest degree of a node among all the
nodes in a tree is called as 'Degree of Tree'
9.Level of a tree
▪ The root node is said to be at
Level 0 and the children of root
node are at Level 1 and the
children of the nodes which are
at Level 1 will be at Level 2 and
so on...

10.Depth of a tree
▪ The total number of edges from root node to a particular node is called
as DEPTH of that Node.
▪ In a tree, depth of the root node is '0'
11.Height of a tree
• The total number of edges from leaf node to a particular node in the
longest path is called as height of a tree
• Height of the root node is said to be height of the tree.
• Height of all leaf nodes is '0'.

12. Sub Tree


▪ Each child from a node forms a
subtree recursively.
▪ Every child node will form a
subtree on its parent node.

Types of Trees
TWO TYPES
• General tree
• Binary Tree

1. General tree
In the general tree, a node can have either 0 or
maximum n number of nodes. There is no
restriction imposed on the degree

2. Binary Tree ▪ A binary tree is a special type of tree in which every


node can have a maximum of 2 children.
▪ One is known as a left child and the other is known
as right child.
▪ In a binary tree, every node can have either 0
children or 1 child or 2 children
Types of Binary Trees
i. Strict Binary Tree
ii. Full Binary Tree
iii. Complete Binary tree
iv. Extended Binary Tree
v. Threaded Binary Tree
1.Strictly Binary Tree(SBT)
▪ In SBT , every node should have
exactly TWO children or none.
▪ That means every internal node must
have exactly two children.
▪ A binary tree in which every node has
either two or zero number of children
is called Strictly Binary Tree

2.Full Binary Tree(FBT)


▪ In SBT, if all leaf nodes are at same
level, then it is called as Full Binary
Tree.
▪ A Binary tree is called as Full Binary
Tree if and only if:
▪ i) Each non leaf node has exactly
TWO children
▪ ii) All leaf nodes are at same level
3.Complete Binary Tree(CBT)
▪ A complete binary tree is a special type of
binary tree where all the levels of the tree
are filled completely except the lowest level
nodes which are filled from as left as
possible.
▪ In CBT all the nodes must have exactly two
children and at every level of complete
binary tree there must be 2level number of
nodes.

Full vs Complete Binary tree

FBT: Every node other than the CBT: Every level, except the last, is
leaves has two children. completely filled
4.Extended Binary Tree
▪ A binary tree can be converted into extended binary-tree by adding dummy
nodes to existing nodes wherever required.
▪ The binary tree to which external nodes are added is called as Extended
Binary Tree.
Representation of Trees
▪A binary tree is represented using two methods
1. Array Representation

2. Linked List Representation

1.Array Representation of BT
▪ In array representation of a binary tree, we use one-dimensional array (1-D
Array) to represent a binary tree.
Advantage:
▪ Easy access of the nodes
Dis-advantage:
▪ wastage of memory
2.Linked List Representation of BT
▪ A double linked list to represent a binary tree in which , every node consists
of three fields.
2.Linked List Representation of BT
▪ The structure defining a node of binary tree in C is as follows.

Struct node
{
struct node *lc ; // points to the left child
int data; // data field
struct node *rc; // points to the right child
}
Tree Traversals
• Traversal is a technique for visiting all of a tree's nodes and printing their
values.
• Traversing a tree involves iterating over all nodes in some manner
• We always start from the root (head) node since all nodes are connected by
edges (links).

• There are three types of traversal of a binary tree. .


1. Inorder (Left, Root, Right)-> LRR
2. Preorder (Root, Left , Right)-> RLR
3. Postorder (Left , Right, Root)-> LRR
1.Inorder Traversal : Left, Root, Right
▪ The left subtree(left node) is visited first, followed by the root,
and finally the right subtree(right node) in this traversal
strategy.
▪ The output of a binary tree traversal in order produces sorted
key values in ascending order
Example
Algorithm: In-order Traversal
Step 1: Recursively traverse the left subtree
Step 2: Now, visit the root
Step 3: Traverse the right subtree recursively
Algorithm
Step 1: Repeat Steps 2 to 4 while TREE != NULL
Step 2: INORDER(TREE -> LEFT)
Step 3: Write TREE -> DATA
Step 4: INORDER(TREE -> RIGHT)
[END OF LOOP]
Step 5: END

Algorithm Inorder( Tree Node)


{
if (Node == NULL)
return;
Inorder(node->left);
visit node->data ;
Inorder(node->right);
}
Algorithm: Inorder Traversal Example

• print the left most node of the left sub-tree i.e. 23.
• print the root of the left sub-tree i.e. 211.
• print the right child i.e. 89.
• print the root node of the tree i.e. 18.
• Then, move to the right sub-tree of the binary tree and print the left most node i.e.
10.
• print the root of the right sub-tree i.e. 20.
• print the right child i.e. 32.
• hence, the printing sequence will be 23, 211, 89, 18, 10, 20, 32.
int main()
//program to implement in-order traversal in C {
language struct node* root = createNode(40);
#include <stdio.h> root->left = createNode(30);
#include <stdlib.h> root->right = createNode(50);
struct node { root->left->left = createNode(25);
int element; root->left->right = createNode(35);
struct node* left; root->left->left->left = createNode(15);
struct node* right; root->left->left->right = createNode(28);
}; root->right->left = createNode(45);
/*To create a new node*/ root->right->right = createNode(60);
struct node* createNode(int val) root->right->right->left = createNode(55);
{ root->right->right->right = createNode(70);
struct node* Node = (struct node*)malloc(size printf("\n The Inorder traversal of given binary t
of(struct node)); ree is -\n");
Node->element = val; traverseInorder(root);
Node->left = NULL; return 0;
Node->right = NULL; }
return (Node);
}
/*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);
}
2. Pre-order Traversal :Root, Left , Right
▪ In preorder traversal, first, root node is visited, then left sub-tree
and after that right sub-tree is visited.
Algorithm: Preorder
Step 1: Repeat Steps 2 to 4 while TREE != NULL
Step 2: Write TREE -> DATA
Step 3: PREORDER(TREE -> LEFT)
Step 4: PREORDER(TREE -> RIGHT)
[END OF LOOP]
Step 5: END

Algorithm preorder( Tree Node)


{
if (Node == NULL)
return;
visit node->data ;
preorder(node->left);
preorder(node->right);
}
Algorithm: Preorder Traversal Example

After the completion of preorder traversal, the final output is -


40, 30, 25, 15, 28, 35, 50, 45, 60, 55, 70
//implement preorder traversal
#include <stdio.h>
#include <stdlib.h> int main()
{
struct node { struct node* root = createNode(40);
int element; root->left = createNode(30);
struct node* left; root->right = createNode(50);
struct node* right; root->left->left = createNode(25);
}; root->left->right = createNode(35);
/*To create a new node*/
root->left->left->left = createNode(15);
struct node* createNode(int val) root->left->left->right = createNode(28);
{ root->right->left = createNode(45);
struct node* Node = (struct node*)malloc(sizeof(struct n root->right->right = createNode(60);
ode)); root->right->right->left = createNode(55);
Node->element = val; root->right->right->right = createNode(70);
Node->left = NULL;
Node->right = NULL; printf("\n The Preorder traversal of given binary
tree is -\n");
return (Node); traversePreorder(root);
} return 0;
}
/*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);
}
3.Postorder Traversal : Left , Right, Root
▪ It follows the principle LRN (Left-right-node)
Algorithm: Postorder
Step 1: Repeat Steps 2 to 4 while TREE != NULL
Step 2: POSTORDER(TREE -> LEFT)
Step 3: POSTORDER(TREE -> RIGHT)
Step 4: Write TREE -> DATA
[END OF LOOP]
Step 5: END

Algorithm postorder( Tree Node)


{
if (Node == NULL)
return;
Postorder(node->left);
Postorder(node->right);
visit node->data ;
}
Algorithm: Post-order Traversal Example

After the completion of preorder traversal, the final output is -


{15, 28, 25, 35, 30, 45, 55, 70, 60, 50, 40}
//implement postorder traversal
#include <stdio.h> int main()
#include <stdlib.h> {
struct node* root = createNode(40);
struct node { root->left = createNode(30);
int element; root->right = createNode(50);
struct node* left;
struct node* right;
root->left->left = createNode(25);
}; root->left->right = createNode(35);
root->left->left->left = createNode(15);
/*To create a new node*/ root->left->left->right = createNode(28);
struct node* createNode(int val) root->right->left = createNode(45);
{ root->right->right = createNode(60);
struct node* Node = (struct node*)malloc(sizeof(struct n root->right->right->left = createNode(55);
ode)); root->right->right->right = createNode(70);
Node->element = val;
Node->left = NULL; printf("\n The Preorder traversal of given binary
Node->right = NULL; tree is -\n");
return (Node);
traversePreorder(root);
} return 0;
}

/*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);
}
Representation of Algebraic expression
▪ An algebraic expression is a mathematical expression where
variables and constants are combined using the operational (+, -, ×
& ÷) symbols.
▪ An Expression tree used to represent the Algebraic Expression
Expression Tree
▪ The expression tree is a binary tree in which
each internal node corresponds to the operator
and each leaf node corresponds to the
operand.
ex.3 + ((5+9)*2)
▪ In-order traversal of expression tree produces
infix version of given postfix expression (same
with post-order traversal it gives postfix
expression)
Expression Tree
Construction of Expression Tree:

▪ For constructing an expression tree, we use a stack.


▪ Convert an Infix expression -> Postfix expression.
▪ We loop through input postfix expression and do the following for
every character.
1. If (character ==operand) → push that into the stack
2. If (character == operator) →
a) pop two values from the stack,
b) Consider operator as root node make them its
children(right and left).
c) Push the tree as element into stack
3. Repeat the process until all characters from postfix expression
4. In the end, the only element of the stack will be the root of an
expression tree.
Expression Tree
Example:
Infix Expression: A+B
Postfix: AB+
Character stack Obs
A A push(A)
B AB push(B)
+ + pop(),perform + and push(+)
Expression Tree
Example:
Infix Expression: (A+B)*(C-D)
Postfix: AB+CD-*
Character stack Obs
A A push(A)
B AB push(B)
+ pop(),perform + and push(+)

C C push(C)
D CD push(D)
- pop(),perform + and push(-)

*
Threaded Binary Tree(TBT)
▪In a Threaded Binary Tree(TBT), NULL pointers are replaced
by references of other nodes in the tree.
▪These extra references are called as threads
Threaded Binary tree(TBT) contd..
▪ Threaded Binary Tree is also a binary tree in which all left child
pointers that are NULL points to its in-order predecessor, and all
right child pointers that are NULL points to its in-order successor.
Heap Data Structure –(Balanced Binary Tree)
▪ Heap is a special case of balanced binary tree data structure
where the root-node (key) is compared with its children and
arranged accordingly.
▪ Min-Heap
▪ Max-Heap

1.Min-Heap(Min Binary Heap)

▪ It is Binary Tree where the


value of the root node is less
than or equal to either of its
children.
i. e. A[Parent(i)] <= A[i]
2.Max-Heap(Max-Binary Heap)
• The Binary Tree where the value
of the root node is greater than
or equal to either of its children.
• A[Parent(i)] >= A[i]

Operations on Heap
The following operations are performed on the heap
1. Insertion (max heap tree and min heap tree)
2. Deletion(max heap tree and min heap tree)
Operations on Heap- Insertion on Max Heap Tree
▪ To create the max heap tree, we need to consider the following two
cases:
▪ First, we have to insert the element in such a way that the property
of the complete binary tree must be maintained.
▪ Secondly, value(parent node) >= the either of its child.

Alg
▪ Step 1 - Insert the newNode as last leaf from left to right.
▪ Step 2 - Compare newNode value with its Parent node.
▪ Step 3 - If (newNode value > its parent) → swap both of them.
▪ Step 4 - Repeat step 2 and step 3 until newNode less than its parent node
(or) newNode reaches to root.
Operations on Heap- Insertion on Max Heap Tree
Create a max heap tree 44, 33, 77, 11, 55, 88, 66

77 added to the right of the 44


add the 44 and swapped as 11 is added to left of 33
33 added to left of A[Parent(i)] >= A[i]
55 to the right of 33 make
44
55 as parent bcoz
A[Parent(i)] >= A[i]

add 88 to the left of 44


and swap 44 with 88 swap 77 with 88
add the 66 element to the right
side of 77
/* C program to build a binary heap */
#include <stdio.h> void maxheapify(int a[], int i, int heapsize)
#include <stdlib.h> {
#define MAX 20 int temp, largest, left, right, k;
void maxheapify(int *, int, int); left = (2*i+1);
int* buildmaxheap(int *, int); right = ((2*i)+2);
void main() if (left >= heapsize)
{ return;
int i, t, n; else {
int *a = calloc(MAX, sizeof(int)); if (left < (heapsize) && a[left] > a[i])
int *m = calloc(MAX, sizeof(int)); largest = left;
printf("Enter no of elements \n"); else
scanf("%d", &n); //read n largest = i;
printf("Enter the elements of tree\n"); if (right < (heapsize) && a[right] > a[largest])
for (i = 0; i < n; i++) { largest = right;
scanf("%d", &a[i]); if (largest != i) {
} temp = a[i];
m = buildmaxheap(a, n); a[i] = a[largest];
printf("The heap is\n"); a[largest] = temp;
for (t = 0; t < n; t++) { maxheapify(a, largest, heapsize);
printf("%d\n", m[t]); }
}} }
int* buildmaxheap(int a[], int n) }
{
int heapsize = n;
int j;
for (j = n/2; j >= 0; j--) {
maxheapify(a, j, heapsize);
}
return a;
}
Operations on Heap - Insertion on Min Heap Tree
▪ To create the min heap tree, we need to consider the following two
cases:
▪ First, we have to insert the element in such a way that the property
of the complete binary tree must be maintained.
▪ Secondly, value(parent node) <= the either of its child.

ALG:
▪ Step 1 - Insert the newNode as last leaf from left to right.
▪ Step 2 - Compare newNode value with its Parent node.
▪ Step 3 - If (newNode value < its parent) → swap both of them.
▪ Step 4 - Repeat step 2 and step 3 until newNode less than its parent node
(or) newNode reaches to root.
Operations on Heap- Insertion on Min Heap Tree
Create a min heap tree 10, 40, 50, 5

Insert 0
Insert 50
Insert 40

Insert 5 Insert 5
Swap as node<parent Swap as node<parent
Deleting on Max Heap Tree
Step 1 − Remove root node.
Step 2 − Move the last element of last level to root.
Step 3 − Compare the value of this child node with its parent.
Step 4 − If (parent < child), → swap them.
Step 5 − Repeat step 3 & 4 until Heap property holds.

Remove root node and make 14 as root Compare 14 with its children.14< 48 -> swap

Compare 14 with its children.14< 33 -> swap Compare 14 with its children.14< 26 -> swap
Deleting on Max Heap Tree
Deleting on Min Heap Tree
Step 1 − Remove root node.
Step 2 − Move the last element of last level to root.
Step 3 − Compare the value of this child node with its parent.
Step 4 − If (parent > child), → swap them.
Step 5 − Repeat step 3 & 4 until Heap property holds.

Ex.

When deleting the root node, the last node


becomes the new root node. Since 48 is larger than its children, it needs to trickle
down into the correct position.
Deleting on Min Heap Tree
Next, 5 and 8 are compared to obtain
A comparison is made of the two children, 4 and 7, and
the smallest child of 48 again
the smallest value is chosen. Since 4 is smaller than 48,
they swap positions.

Finally, 11 and 6 are compared. Node 6


is the smallest child. swap 48 and 6

You might also like