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

Data Structures Unit-III Lecture Notes

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

Data Structures Unit-III Lecture Notes

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

Data Structures

Mr. Pandu Sowkuntla


Asst. Professor,
Dept. of CSE, SRM University AP

Data Structures--> Unit-III: Pandu Sowkuntla 1


TREES

UNIT-III
Introduction to Trees
Why Tree data structure?
► Linear data structure:
Array • Stores the data one after the other (for
17 23 97 44 33 an element we can find before element and
after element).
0 1 2 3 4 5 6 7
► Choosing an appropriate data structure:
• Best suited for problem scenario
• Cost of common operations
• Space utilization

► Tree data structure used to:


• Store the data hierarchical
(Ex: File System in an Operating System)
• Organize the data for quick insertion,
deletion and search (Ex: Binary Search
Algorithm)
• Solve complex problems (Ex: Network
routing Algorithms)

Pandu Sowkuntla
3
Data Structures--> Unit-III:
Introduction to Trees
What is Tree data structure ? Dean Root
Leaves

Branches
HOD1 HOD2

Leaves
Emp1 Emp2 Emp2

Root
Branches Std1 Std2 Std3 Std4 Std5

Logical representation of Tree data structure

Tree data structure is an efficient way of storing and


organizing the data that is naturally hierarchical.
OR
Tree data structure is a non-linear (hierarchical) data
structure that consists of nodes with parent-child relationship.
Pandu Sowkuntla
4
Data Structures--> Unit-III:
Introduction to Trees
Root
Terminalogy used in Tree data structure
n1 Level-0
Intermediate or
Internal nodes Links(Edges)
► A node can contain any type
of data (Like Linked lists) n2 n3 Level-1

► The root (n1) is the parent


of n2 and n3 nodes
► Root is the only node which n6 Level-2
n4 n5
does not have parent node

n7 n8 n9 n10 n11 n12


Level-3
► n2 and n3 are children nodes of root node n1
► n4 and n5 are children nodes of n2 and grand
children of n1. And n4 and n5 are siblings. Leaf nodes (Do not have
► n1 and n2 are ancestors of n4, n5, n7, n8 and n9 nodes. parent node)
► n4 and n5 are descendants of n2 node.
► Nodes not having same parent with same grand parent are called cousins (Ex: n8 and n9) 5
Data Structures--> Unit-III: Pandu Sowkuntla
Introduction to Trees Height of node
Properties of Tree data structure Root n3=2 Height n6 is: 1
n1 and n1 is: 3
1. Tree is a recursive data structure
• Height of root
n1 node is Height
Depth of node of Tree
Sub n5=2 n2 n3
trees • Height of a tree
with one node=0
T1 T2 T3
• Height of an
n4 n5 n6 empty tree=-1

2. Degree of a node is the no. of


children that a node has. n7 n8 n12
n9 n10 n11

3. If Tree contains n nodes then it contains n-1 edges


(A tree does not have cycles).

4. Depth of a node X is length (number of edges) of the path from the root node to X

5. Height of a node X is number of edges in longest path from the node X to a leaf node
Pandu Sowkuntla
6
Data Structures--> Unit-III:
Introduction to Trees *left Root:n1 data
*right
Implementation of Tree data structure:
Binary Trees n2 n3

n1 n4 n5 n6

n7 n8 n9 n10 n11
n2 n3

n6 struct Node
n4 n5 {
struct Node *left;//to store address of left child
int data;
n7 n8 n9 n10 n11 struct Node *right;//to store address of left child
};
Note: Nodes are created dynamically

• A tree in which each node has at most two children is called as Binary Tree.
(No. of Children <= 2)
Pandu Sowkuntla
7
Data Structures--> Unit-III:
Binary Trees
n1
n1 n1 n1
n2
n2 n3 n2 n3

n4 n5
n4 n5 n6 n4
n5
n7
n7 n8 n9 n10 n7

Strict Binary Tree or Proper or Full Binary Tree: In Strict Binary Tree, each node can
n1 n1 have either zero or 2 nodes
n1
n2 n3 n2 n3
n2 n3
n4 n5 n6 n7 n4 n5 Not a Strict Binary Tree
n4
Strict Binary Tree Strict Binary Tree
Pandu Sowkuntla
8
Data Structures--> Unit-III:
Complete Binary Trees
In Complete Binary Tree, all the levels except possibly last are filled and all nodes are
as left as possible.

Level-0 n1 n1 n1

Level-1 n2 n3 n2 n3 n2 n3

Level-2 n4 n5n6 n7 n4 n5 n4 n5
Complete Binary Tree Complete Binary Tree Not a Complete Binary Tree
Nodes are missing here
(two vacant positions)

n1 n1 Maximum number of nodes in complete


Binary tree at level-i = 2i
n2 n3 n2 n3

n4n5 n6 n4 n5n6
Not a Complete Binary Tree Complete Binary Tree

Pandu Sowkuntla
9
Data Structures--> Unit-III:
Perfect Binary Trees
In Perfect Binary Tree, all the levels are filled.
With “n” nodes in Perfect binary tree, what is the
Level-0 height (h) of the tree?
n1
Maximum no. of nodes in a binary tree with the height “h”,
Level-1 n2 n3
= 20 + 21 +. . . . +2h
Level-2 n4 n5n6 n7 = 1 + 2h+1 -2
Perfect Binary Tree = 2h+1 -1

n = 2h+1 -1
n1
n+1 = 2h+1
n2 n3 log(n+1) = log(2h+1)
log(n+1) = (h+1)
n4 n5 h = log(n+1)-1
Complete Binary Tree
but not Perfect

Pandu Sowkuntla
10
Data Structures--> Unit-III:
Balanced Binary Trees or Height balanced binary trees
A Binary tree said to be if:
1. The height difference between the left and the right subtree for any node is not more
than K (usually K=1).
2. The left subtree is balanced.
3. The right subtree is balanced.
Height diff = | Height of left child – Height of right child |

diff=2 diff=0
diff=1
n1 n1
n1
diff=1 diff=0 diff=0 diff=0
diff=0 diff=0
n2 n3 n2 n3
n2 n3
diff=0 diff=0 diff=0 diff=0 diff=0
diff=0 diff=0
n4 n5 n4 n5
n4 n5 n6

Balanced binary tree diff=0 Balanced binary tree


n6
Not a Balanced binary tree
Pandu Sowkuntla
11
Data Structures--> Unit-III:
Binary Search Trees (BST)
BST is a binary tree where each node n satisfy the following:
• Every node in the left subtree of n contains a value which is smaller than the
value in n.
• Every node in the right subtree of n contains a value which is larger than the
value in n.

8 8 8

3 10 3 3 10
10

1 6 14 6 1 6
1

4 7 13 4 2

Binary Search Tree Not a Binary Search Tree


Binary Search Tree

Pandu Sowkuntla
12
Data Structures--> Unit-III:
Binary Search Trees (BST)
► Empty BST is a single pointer with the value of NULL. int main()
root = NULL; {
► A node in BST can be declared as: struct node *root;
root=NULL;
struct Node insert(root,45);
{ insert(root,15);
struct Node *leftChild; //to store address of left child insert(root,79);
int data; insert(root,90);
struct Node *rightChild; //to store address of left child insert(root,10);
}; insert(root,55);
► Create a node of BST as: insert(root,12);
insert(root,50);
struct Node *newNode(int item)
}
{
struct node *newnode = (struct Node*) malloc(sizeof(struct Node));
newnode->data = item;
newnode->leftChild = NULL;
newnode->rightChild = NULL;
return newnode;
} Pandu Sowkuntla
13
Data Structures--> Unit-III:
Inserting data into BST Elements: 45, 15, 79, 90, 10, 55, 12, 50
Step-1:45 root Step-4:90, int main(){
45 90>45, struct node *root;
45
90>79 root=NULL;
\0 \0 insert(root,45);
15 79 insert(root,15);
Step-2:15, 15<45 insert(root,79);
\0 insert(root,90);
45 \0 \0 90
insert(root,10);
insert(root,55);
\0 \0 \0 insert(root,12);
15
insert(root,50);
Step-5:10, }
Step-6:55,
\0 \0 10<45, 45 45
55>45,
10<15
Step-3:79, 79>45 55<79
15 79 15 79
45

10 \0 \0 90 10 \0 55 90
15 79

\0 \0 \0 \0 \0 \0 \0 \0 \0 \0
\0 \0 \0 \0
Pandu Sowkuntla
14
Data Structures--> Unit-III:
Binary Search Trees (BST) Elements: 45, 15, 79, 90, 10, 55, 12, 50
void insert_BST(struct Node *root,int item){
if(root == NULL){ //if tree is empty Step-1:45 root
root = newNode(item); 45
}
else{ \0 \0
current = root;
45
parent = NULL;
while(1){
parent = current; Step-2:15, 15<45
15 79
if(item < parent->data){//go to left of the tree 45
current = current->leftChild;
if(current == NULL){ //insert to the left \0 \0 \0 90
parent->leftChild = newNode(item); 15 \0
return;
} \0 \0
}
else{ //go to right of the tree Step-3:79, 79>45 Step-4:90,
current = current->rightChild;//insert to the right 45 90>45
if(current == NULL){ 90>79
parent->rightChild = newNode(item);
return; 15 79
}
} \0 \0 \0 \0 15
Data Structures--> Unit-III: Pandu Sowkuntla
} } }
Binary Search Trees (BST)
struct node *root;
int main()
45
{
displayBST(root);
79 if(searchBST(root, item)==TRUE)
15
printf(“Found”);
else
10 \0 55 90 printf(“Not Found”);
}
\0 12 50 \0 \0 \0

bool searchBST(struct Node *root, int item)


{
void displayBST(struct Node *root)
if(root==NULL)
{
return FALSE;
printf(“BST elements are:”)
else if(root->data==item)
if(root!=NULL)
return TRUE;
{
else if(item<root->data)
displayBST(root->leftChild);
searchBST(root->leftChild, item);
printf("%d\n", root->data);
else
displayBST(root->rightChild);
searchBST(root->rightChild, item);
}
}
}
Pandu Sowkuntla
16
Data Structures--> Unit-III:
Binary Search Trees (BST)
struct node *root;
void minBST(struct Node *root) int main()
{ {
if(root==NULL) min=minBST(root);
printf(“Empty Tree”); printf(“Min val=%d”, min);
return -1; ht=maxBST(root);
else if(root->left==NULL) printf(“Height=%d”, ht);
return root->data;
else }
minBST(root->left);
} void maxBST(struct Node *root)
{
45

15 79

10 \0 55 90

\0 12 \0 \0 }
50 \0

Pandu Sowkuntla
17
Data Structures--> Unit-III:
Binary Tree Traversal

17 23 97 44 33
0 1 2 3 4 5 6 7
Traversal in a Linked list: from head to NULL
Traversal in an array:
from a[0] to a[n-1]
Linear Traversal root
Tree traversal: Process of visiting (reading or processing data) F Level-0
each node in the tree exactly once in some order.

Tree traversal J Level-1


D
Breadth First Traversal
(Level-order traversal): F, D, J, B, E, G, K, A, C, I, H B E G K Level-2

Depth First Traversal


1. Preorder A C I Level-3
<root, left, right>: F, D, B, A, C, E, J, G, I, H, K
2. Inorder
H Level-4
<left, root, right>: A, B, C, D, E, F, G, H, I, J, K
3. Postorder root-> Print the value,
<left, right, root>: A, C, B, E, D, H, I, G, K, J, F left-> Traverse left sub tree,
right-> Traverse right subtree
Pandu Sowkuntla
18
Data Structures--> Unit-III:
Binary Tree Traversal
void preorder(struct Node *root) root
{
if(root == NULL) F
return;
printf("%d ",root->data); //visit the node J
D
preorder(root->left); //traverse the left subtree
preorder(root->right); //traverse the right subtree
} B E G K
void inorder(struct Node *root)
{ A C I
if(root == NULL)
return;
inorder(root->left); //traverse the left subtree H
printf("%d ",root->data); //visit the root
inorder(root->right); //traverse the right subtree
}
void postorder(struct Node *root)
{
if(root == NULL) return;
postorder(root->left); //traverse the left subtree
postorder(root->right); //traverse the right subtree
printf("%d ",root->data); //visit the root
19
} Data Structures--> Unit-III: Pandu Sowkuntla
Binary Tree Traversal

A Preorder:

B C
Inorder:

D E F

Postorder:
G H I

Pandu Sowkuntla
20
Data Structures--> Unit-III:
Deletion in Binary Search Tree
Three situations arise in deleting a node from binary search tree.
Case-I: The node to be deleted is a leaf node Case-II: The node to be deleted has only one child.

Step-1: Replace the node with its child and delete the
child node (which now contains the value which is to
Step: Replace the leaf node with the NULL
be deleted).
and simple free the allocated space.
Step-2: Simply replace it with the NULL and free the
allocated space.

Pandu Sowkuntla
21
Data Structures--> Unit-III:
Deletion in Binary Search Tree

Case-III: The node to be deleted


has two children.

Step-1: Identify the in-order


successor of the given node
(i.e., a node just greater than
the given node)

Step-2: Replace the given node


with the in-order successor
node.

Step-3: Delete in-order


successor node

Pandu Sowkuntla
22
Data Structures--> Unit-III:
Binary Search Tree

Complexity Analysis:
8
► Searching: Searching in binary search 8
tree has worst case complexity of O(n).
In general, the time complexity is O(h)
where h is the height of BST.
10
3 10
► Insertion: Insertion in binary search
tree has the worst-case complexity of 14
O(n). In general, the time complexity is 1 6 14
O(h).
8

► Deletion: Deletion in binary tree has 16


worst case complexity of O(n). In 7 4 7 13
general, the time complexity is O(h).
Balanced BST
17
5 Right Skewed BST

Left Skewed BST


2 23
Data Structures--> Unit-III: Pandu Sowkuntla
AVL Trees
Why AVL Trees ?
8
8 8

10
7 3 10

14
5 1 6 14

16
3
Left Skewed Right Skewed 4 7 13
Binary Search Tree Binary Search Tree
2 17 Balanced Binary Search Tree
Unbalanced Binary Search Trees

Insertion, Deletion or Search operations


take O(n) time in unbalanced BSTs. Cost can be reduced to O(log n) with
balanced BSTs.

Pandu Sowkuntla
24
Data Structures--> Unit-III:
AVL (Adelson, Velskii & Landis) Trees

What is AVL Tree (or Height balanced binary search tree) ?

AVL tree is a balanced BST in which the height of left and right subtrees differ by no
more than one.

► AVL tree is a BST that is either empty or consists of two AVL subtrees,
Left subtree TL and right subtree TR whose heights differ by ≤1.

► The height difference is called Balance Factor.


BF=0
► Balance factor for any node in AVL tree must be +1, 0, (or) -1.
28
HL-HR < = 1
BF=0 BF=-1
AVL tree ensures that Insertion, Deletion and Search 10 36
operations take O(log n).
BF=0 BF=0 BF=0
8 21 50

AVL Tree
Pandu Sowkuntla
25
Data Structures--> Unit-III:
AVL Tree Rotations

► In AVL tree, after performing operations like insertion or deletion, the balance factor of
every node in the tree should be maintained.

► If tree becomes imbalanced due to any operation, the rotation operations are performed to
make it balanced.

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


Single
rotation
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


Double
rotation
4) R L rotation : Inserted node is in the left subtree of right subtree of A

Here node A is the critical node (closest ancestor) whose balance Factor is other
than -1, 0, 1

Pandu Sowkuntla
26
Data Structures--> Unit-III:
AVL Tree Rotations
1. L L Rotation (Single Left Rotation)

Imbalanced AVL tree L L Rotation Balanced AVL tree after rotation


(Clockwise Rotation)
2. R R Rotation (Single Right Rotation)

Imbalanced AVL tree R R Rotation Balanced AVL tree after rotation


(Anti Clockwise Rotation) Pandu Sowkuntla
27
Data Structures--> Unit-III:
AVL Tree Rotations
3. L R Rotation (Left Right Rotation)

Balanced AVL tree


Imbalanced AVL tree Anti Clockwise Rotation Clockwise Rotation after rotation

4. R L Rotation (Right Left Rotation)

Anti Clockwise Rotation Balanced AVL tree


Imbalanced AVL tree Clockwise Rotation
after rotation

Pandu Sowkuntla
28
Data Structures--> Unit-III:
Insertion on AVL Tree
Example-1: Insert 1 to 8 numbers into AVL Tree

Insert 1 Insert 2 Insert 3 LL Rotation

Insert 4
Insert 5, LL Rotation

Pandu Sowkuntla
29
Data Structures--> Unit-III:
Insertion on AVL Tree

Insert 6
Balanced AVL tree
Insert 6, L L Rotation after rotation

Insert 7 L L Rotation
Balanced AVL tree Insert 8,
after rotation Balanced AVL tree
Example-2: Insert the following elements into AVL Tree: 50, 20, 60, 10, 8, 15, 32, 46, 11, 48.
Pandu Sowkuntla
30
Data Structures--> Unit-III:
Deletion on AVL Tree
Steps for deleting a node in an AVL tree.
Step-1: Search node in the tree by the BST logic. If the element is not present, then return.

▪ Case-I: The node to be deleted is a leaf node


▪ Replace the leaf node with the NULL and simple free the allocated space.

▪ Case-II: The node to be deleted has only one child.


▪ Replace the node with its child and delete the child node (which now contains the
value which is to be deleted).

▪ Case-III: The node to be deleted has two children.


▪ Replace the given node with the in-order successor node.

Step-2: Delete the node.

Step-3: While retracing, calculate and check the balance factor of each ancestor node.

Step-4: Remove the imbalance using rotations

Step-5: Repeat the step 3 till the root of the tree

Pandu Sowkuntla
31
Data Structures--> Unit-III:
Deletion on AVL Tree

Pandu Sowkuntla
32
Data Structures--> Unit-III:
AVL Trees
Complexity Analysis:

Pandu Sowkuntla
33
Data Structures--> Unit-III:
Expression Trees
It is a binary tree that represents an expression with the following properties:
• Each leaf is an operand. Ex: a, b, c, 5, 10
• The root and internal nodes are operators. Ex: +, -, *, /, ^
• Subtrees are subexpressions with the root being an operator.
Example expression:
a + (b * c) + d * (e + f) An infix expression can be produced by performing
in-order traversal on expression tree
Equivalent Expression Tree:
(a+(b*c))+(d*(e + f))
+
A prefix expression can be produced by performing
pre-order traversal on expression tree
+ *
+ + a * b c * d + e f

a * d +
A postfix expression can be produced by performing
post-order traversal on expression tree

b c e f a b c * + d e f + * +

Pandu Sowkuntla
34
Data Structures--> Unit-III:
Expression Trees
Constructing Expression tree from postfix expression
Example: a b + c *
Step-1: Read one symbol at a time from
the postfix expression.

Step-2: Check if the symbol is an


operand or operator.

Step-3: If the symbol is an operand,


create a node tree and push it onto a
stack

Step-4: If the symbol is an operator,


pop two pointers from the stack namely
T1 & T2 and form a new tree with root as
the operator, T1 & T2 as a left and
right child

Step-5: A pointer to this new tree is


pushed onto the stack

Pandu Sowkuntla
35
Data Structures--> Unit-III:
Expression Trees
+

+ *

10 * 5 +

2 3 4 6

Infix expression:
Postfix expression evaluation:

Prefix expression:

Postfix expression:

Pandu Sowkuntla
36
Data Structures--> Unit-III:
Array Representation of Complete Binary Tree

Tree Structure: Array indices carry tree structure

Parent of a[k] = a[(k-1)/2]

Left child of a[k] = a[2*k+1]

Right child of a[k] = a[2*k+2]

Array index order = level order (beginning with 0)

If parent node is at index k in the array then

left child of that node is at index (2*k + 1)

right child is at index (2*k+ 2) in the array.


Pandu Sowkuntla
37
Data Structures--> Unit-III:
Pandu Sowkuntla
38
Data Structures--> Unit-III:

You might also like