Download as pdf or txt
Download as pdf or txt
You are on page 1of 69

Course: Data Structures &

its Applications(18IS33)

Lecture Slides by
Prof. Swetha S
Types of Data Structures
Trees
"A tree may grow a
thousand feet tall, but
its leaves will return to
its roots."
-Chinese Proverb
Tree – a Hierarchical Data Structure
• Trees are non linear data structure that can be represented in a
hierarchical manner.
A tree contains a finite non-empty set of elements.
Any two nodes in the tree are connected with a relationship of
parent-child.
Every individual elements in a tree can have any number of sub
trees.
Roo A
t

B C
Left Righ
Sub t
Tree D E F Sub
Tree
Tree – Terminology.
Root : The basic node of all nodes in the tree. All operations on the tree are performed with passing root
node to the functions.( A – is the root node in above example.)
Child : a successor node connected to a node is called child. A node in binary tree may have at most two
children. ( B and C are child nodes to the node A, Like that D and E are child nodes to the node B. )
Parent : a node is said to be parent node to all its child nodes. ( A is parent node to B,C and B is parent
node to the nodes D and F).
Leaf : a node that has no child nodes. ( D, E and F are Leaf nodes )
Siblings : Two nodes are siblings if they are children to the same parent node.
Ancestor : any predecessor node on the path from root to that node ( A,B is ancestor node to D ).
Descendent : any Successor node on the path from that node to leaf node( B,C,D, E and F are descendent
nodes of node A)
Level of a node : The distance of a node from the root node, The root is at level – 0,( B and C are at Level 1
and D, E, F have Level 2 ( highest level of tree is called height of tree )
Degree of node : The number of nodes connected to a particular parent node.
Tree – Terminology.

• Degree of tree: maximum degree among all nodes


• Depth of node: length of path from root to that node
• Height of node: number of edges in the longest path from that node
to a leaf.
• Level of a node =depth of a node
• Height of a tree=level of the tree
Tree Visualization A

B C D

E F G H I J

K L M

N O
CS314 Binary Trees 7
Binary Trees
• There are many variations on trees but we will start with binary trees
• binary tree: each node has at most two children
• the possible children are usually referred to as the left child and the right
child

parent

left child right child

CS314 Binary Trees 8


• Maximum number of nodes at any level i= 2i
• Maximum number of nodes at height h= 2 h+1 -1
• Minimum number of nodes at height h=h+1
• Find the minimum height of the tree given maximum number of
nodes?

log2(n+1) -1
Find the maximum height of the tree given minimum number of
nodes?
n-1
Types of Binary tree
• Full/proper/strict Binary Tree
• Complete binary tree
• Perfect binary tree
Full/proper/strict Binary Tree
• full binary tree: a binary tree is which each node has exactly 2 or 0
children

CS314 Binary Trees 11


• Number of leaf nodes= number of internal node+1
• Maximum number of nodes at any level i= 2i
• Maximum number of nodes at height h= 2 h+1 -1.
• Minimum number of nodes at height h=2h+1
• Find the minimum height of the tree given maximum number of
nodes?

log2(n+1) -1
• Find the maximum height of the tree given minimum number of
nodes?
(n-1)/2
Complete Binary Tree
• complete binary tree: In a complete binary tree, all the levels of a
tree are filled entirely except the last level. In the last level, nodes
might or might not be filled fully. Also, let’s note that all the nodes
should be filled from the left.

Where would the next node go


to maintain a complete tree?
CS314 Binary Trees 14
• Maximum number of nodes at height h= 2 h+1 -1.
• Minimum number of nodes at height h=2h
• Find the minimum height of the tree given maximum number of
nodes?
• log2(n+1) -1
• Find the maximum height of the tree given minimum number of
nodes?
Log n
Perfect Binary Tree
• perfect binary tree: a binary tree with all leaf nodes at the same level.
All internal nodes have exactly two children.
• a perfect binary tree has the maximum number of nodes for a given
height
• a perfect binary tree has (2(h+1) - 1) nodes where h is the height of the
tree
• height = 0 -> 1 node
• height = 1 -> 3 nodes
• height = 2 -> 7 nodes
• height = 3 -> 15 nodes

CS314 Binary Trees 16


Implementation of Binary Tree
struct node
{ struct node *ll;
int data;
struct node &rl;
}
main ()
{ struct node*root =NULL;
root=create();
}
Implementation of Binary Tree
struct node * create()
{
struct node * newnode;
newnode= (struct node*)malloc(size of(struct node))
printf(“Enter the data to be entered or -1 for no node”);
scanf(“%d”, &a);
if (a==-1)
{ return(NULL); }
newnode->data= a;
printf(“ enter the left child of %d”,a);
newnode->ll= create();
printf(“ enter the right child of %d”,a);
newnode->rl= create();
return(newnode);
}
Binary Tree Representation
Arigh A
left
t
chil
chil
d
d
B C
Brigh Crigh
left left
t t
chil
chil
chil
chil D E F
d d
d d

Drigh E righ F righ


left left left
t t t
chil chil chil
chil chil chil
d d d
d d d
Binary Tree Traversal
• Traversal is the process of visiting every node once
• Visiting a node entails doing some processing at that node, but when
describing a traversal strategy, we need not concern ourselves with
what that processing is.

CS 103 20
Binary Tree Traversal Techniques
• Three recursive techniques for binary tree traversal
• In each technique, the left subtree is traversed recursively, the right
subtree is traversed recursively, and the root is visited
• What distinguishes the techniques from one another is the order of
those 3 tasks

CS 103 21
Preoder, Inorder, Postorder
• In Preorder, the root Preorder Traversal:
1. Visit the root
is visited before (pre)
2. Traverse left subtree
the subtrees traversals 3. Traverse right subtree
• In Inorder, the root is Inorder Traversal:
visited in-between left 1. Traverse left subtree
2. Visit the root
and right subtree traversal 3. Traverse right subtree
• In postorder, the root Postorder Traversal:
is visited after (post) 1. Traverse left subtree
2. Traverse right subtree
the subtrees traversals
3. Visit the root
CS 103 22
Illustrations for Traversals
• Assume: visiting a node 1

is printing its label 3 7

• Preorder:
5 8 9
1 3 5 4 6 7 8 9 10 11 12
10
4 6
• Inorder:
4 5 6 3 1 8 7 9 11 10 12 11 12

• Postorder:
4 6 5 3 8 11 12 10 9 7 1

CS 103 23
Illustrations for Traversals (Contd.)
• Assume: visiting a node 15
8 20
is printing its data
• Preorder: 15 8 2 6 3 7 2 11 27

11 10 12 14 20 27 22 30 6 10 12 22 30
• Inorder: 2 3 6 7 8 10 11
3 7 14
12 14 15 20 22 27 30
• Postorder: 3 7 6 2 10 14
12 11 8 22 30 27 20 15

CS 103 24
Binary Search Tree
• Binary Search Tree is a node-based binary tree data structure which
has the following properties:
• The left subtree of a node contains only nodes with keys lesser than
the node’s key.
• The right subtree of a node contains only nodes with keys greater
than the node’s key.
• The left and right subtree each must also be a binary search tree.
There must be no duplicate nodes.
Binary Search Trees (BSTs)
• Binary Search Tree Property:
The value stored at
a node is greater than
the value stored at its
left child and less than
the value stored at its
right child
Binary Search Tree Example
8
5
1
5
4 8 1
1 1
1 2 7 6
1 7 0 8
1
1 2
4
3 5 0
NOT A 2
BINARY SEARCH TREE BINARY SEARCH TREE 1
• Properties of Binary Search Tree provides an ordering among keys so
that the operations like search, minimum and maximum can be done
fast.
• If there is no ordering, then we may have to compare every key to
search for a given key.
Binary Search Trees (BSTs)

Where is the
smallest element?
Ans: leftmost element

Where is the largest


element?
Ans: rightmost element
Creation of BST from the given list
• 76,32,7,8,23,56,67,12,35,20,59,21
Basic Operations

• Following are the basic operations of a tree −


Search − Searches an element in a tree.
Insert − Inserts an element in a tree.
Pre-order Traversal − Traverses a tree in a pre-order manner.
In-order Traversal − Traverses a tree in an in-order manner.
Post-order Traversal − Traverses a tree in a post-order manner.
How to search a binary search tree?
(1) Start at the root
(2) Compare the value of
the item you are
searching for with
the value stored at
the root
(3) If the values are
equal, then item
found; otherwise, if it
is a leaf node, then
not found
How to search a binary search tree?
(4) If it is less than the value
stored at the root, then
search the left subtree
(5) If it is greater than the
value stored at the root,
then search the right
subtree
(6) Repeat steps 2-6 for the
root of the subtree chosen
in the previous step 4 or 5
How to search a binary search tree?

Is this better than searching


a linked list?

Yes !! ---> O(logN)


Search − Searches an element in a tree.
Insert Operation

• Whenever an element is to be inserted, first locate its proper


location.
• Start searching from the root node, then if the data is less than the
key value, search for the empty location in the left subtree and insert
the data.
• Otherwise, search for the empty location in the right subtree and
insert the data.
Inorder Traversal
void inorder(Node root)
{
if (root != null)
{
inorder(root->left);
printf(“%d”, root->data);
inorder(root->right);
}
}

12/10/2021 38
Preorder Traversal
void preorder(Node root)
{
if (root != null)
{
printf(“%d”, root->data);
preorder(root->left);
preorder(root->right);
}
}

12/10/2021 39
Postorder Traversal
void postorder(Node root)
{
if (root != null) {
postorder(root->left);
postorder(root->right);
printf(“%d”, root->data);
}

12/10/2021 40
Application of Traversal Sorting a
BST
• Observe the output of the inorder traversal of
the BST example two slides earlier
• It is sorted
• As a general rule, if you output the keys (data)
of the nodes of a BST using inorder traversal,
the data comes out sorted in increasing order

CS 103 44
Find the inorder ,preorder,postorder for the
following BST
Tree
Traversals:
another
example
Delete Operation in BST
• First, find the item; then, delete it
• Binary search tree property must be preserved!!
• We need to consider three different cases:
(1) Deleting a leaf
(2) Deleting a node with only one child
(3) Deleting a node with two children
(1) Deleting a leaf
(2) Deleting a node with
only one child
Inorder predecessor
Inorder successor
(3) Deleting a node with two
children(find max in left subtree)
(3) Deleting a node with two
children(find min in right subtree)

After deletion
Before deleting 15
Try the implementation!!!!
Expression Trees
• A binary expression tree represents an arithmetic
expression.
• In an expression tree each operator is an interior node
whose children are operands or subexpressions. Operands
are in leaf nodes.
Algorithm to Generate Expression Tree from
Infix expression
1) Initialize Two stack 1) tree stack 2) operator stack
2) Scan the infix expression from Left to Right.
3) If scanned symbol is
->operand: construct a node, push node on to the tree stack
->operator:
a. if operator stack is empty
then construct a node and push the node on
operator stack
b. else if operator stack is not empty
Algorithm to Generate Expression Tree from Infix
expression

Until the precedence of top of operator stack is greater than or equal to


precedence of scanned symbol
Pop an node from operator stack and pop 2 nodes from the tree stack
and attach them as the right and left child of the node popped from the
operator stack and push it back to the tree stack.
else Create a node and push it on to operator stack.
4)Until operator stack is not empty
pop an node from operator stack and pop 2 nodes from the
tree stack and attach them as right and left child , and then push it
back to tree stack.
5) Final tree will be on top of the tree stack
Example
1) a+b*c/d
Program to construct expression tree.
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
struct node
{ char info;
struct node *left;
struct node *right;
};
typedef struct node * NODE;
struct stack
{ int *top;
NODE data[10];
};
typedef struct stack STACK;
int precedence(char c)
{
if(c=='^')
return 5;
else if(c=='*'||c=='/')
return 4;
else if(c=='+'||c=='-')
return 3;
else if(c=='(')
return 1;
}
void push(STACK *S, NODE temp)
{
s->data[++(s->top)]=temp;
}
NODE pop( STACK *S)
{ return s->data[(s->top)--];
}
NODE createnode( char item)
{ NODE temp;
temp=(NODE) malloc(sizeof(struct node));
temp->info=item;
temp->left=NULL;
temp->right=NULL;
return temp;
}
NODE Createexptree( char expression[20])
{
STACK Tree, opS;
Tree.top=-1;
opS.top=-1;
char symbol; int i;
NODE temp, t,l, r;
for(i=0; infix[i]!=‘\0’; i++)
{ symbol=infix[i];
temp= createnode(symbol);
if(isalnum(symbol))
push(&Tree, temp);
else
if(opS==-1)
push(&opS, temp);
else
while(opS.top!=-1&&precedence((opS.data[opS.top])->info)
>=precedence(symbol))
{ t=pop(&opS)
r=pop(&Tree);
l=pop(&Tree);
t->right=r;
t->left=l;
push(&Tree,t);
}
push(&opS,temp);
}// end of else
}//end of else
}//end of for
• //step 5
while(opS.top!=-1)
{
t=pop(&opS)
r=pop(&Tree);
l=pop(&Tree);
t->right=r;
t->left=l;
push(&Tree,t);
}
return pop(&Tree);
}// fun end
int main()
{ NODE root=NULL;
char expression[20];
printf(“ read expression”);
scanf(“%s”, expression);
root=createexptree(expression);
// call inorder, postorder, preorder function
return(0);
}
Expression Trees (continued)
• The preorder and postorder traversals of a binary
expression tree produce the prefix and postfix (RPN)
notation for the expression.
• An inorder traversal generates the infix form of the
expression, assuming that parentheses are not needed
to determine the order of evaluation.
Expression Trees (continued)

Preorder(Prefix): - + a / * b c d e
Inorder(Infix): a + b * c / d - e
Postorder(Postfix): a b c * d / + e -

You might also like