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

399_33_powerpoint-slides_Chapter12

The document discusses data structures, specifically focusing on stacks, queues, and trees, detailing their operations and implementations in C. It explains primitive and non-primitive data structures, with stacks and queues being highlighted as examples of linear data structures. The document also covers key operations such as push, pop, enqueue, and dequeue, along with their implementations using arrays and linked lists.

Uploaded by

nirnika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

399_33_powerpoint-slides_Chapter12

The document discusses data structures, specifically focusing on stacks, queues, and trees, detailing their operations and implementations in C. It explains primitive and non-primitive data structures, with stacks and queues being highlighted as examples of linear data structures. The document also covers key operations such as push, pop, enqueue, and dequeue, along with their implementations using arrays and linked lists.

Uploaded by

nirnika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 69

Programming

in C
Pradip Dey & Manas Ghosh

© Oxford University Press 2013. All rights reserved.


CHAPTER Stacks, Queues and
12 Trees

© Oxford University Press 2013. All rights reserved.


OBJECTIVE

understand the operations on stacks and their


usefulness

know about the operations on queues and their usage

learn about different binary trees and their application

© Oxford University Press 2013. All rights reserved.


INTRODUCTION

The logical inter-relation between elementary data


items is called as data structure.
 Basically it deals with the manipulation and organization of
data.
 The major advantages of data structures are listed below.
 It provides different levels of organizing data.
 It tells how data can be stored and accessed in its
elementary level.
Data structures can be classified into
 Primitive data structures
 Non-primitive data structures

© Oxford University Press 2013. All rights reserved.


CLASSIFICATION OF DATA STRUCTURE

Primitive data structures are the data structures


that can be manipulated directly by machine
instructions.
 The integer, real, character, etc., are the
examples of primitive data structures.
In C, the different primitive data structures are int,
float, char, and double.

© Oxford University Press 2013. All rights reserved.


NON-PRIMITIVE DATA STRUCTURES
Non-primitive data structures cannot be
manipulated directly by machine instructions.
 Arrays, linked lists, trees etc., are the examples of non-
primitive data structures.
These data structures can be further classified
into linear and non-linear data structures.
The data structures that show the relationship of
logical adjacency between the elements are called
linear data structures. Otherwise they are called
non-linear data structures.

© Oxford University Press 2013. All rights reserved.


CLASSIFICATION OF DATA STRUCTURE
Stacks, queues, and linear linked lists such as
singly linked list, doubly linked list, etc., are the
examples of linear data structures; whereas trees
and graphs are nonlinear data structures.

While solving a problem, it is needed to represent


relation between its data items. That is why data
structures are used. The logical interrelation
between elementary data items is called as data
structure.

© Oxford University Press 2013. All rights reserved.


KEY WORD

 Binary tree :A tree in which each node can have a


maximum of two children is known as a binary tree.
 Data structure: The logical inter-relation between
elementary data items is called as data structure.
 Deque: A deque is a homogeneous list in which elements
can be added or inserted and deleted or removed from both
the ends.
 Expression tree :An expression tree is a binary tree that
stores an expression in such a way that each leaf node
contains an operand of the expression, and each interior node
contains an operator of the expression.

© Oxford University Press 2013. All rights reserved.


KEY WORD
Heap : A heap is a complete binary tree, each
of whose nodes contains a key which is greater
than or equal to the key in each of its children.
Priority queue: Priority queue is a special
type of queue in which items can be inserted or
deleted based on the priority.
Queue: A queue is an ordered set of
homogeneous elements in which the items are
added at one end (called the rear) and are
removed from the other end (called the front).
Stack: A stack is an ordered collection of
elements into which new elements may be
inserted and from which elements may be
deleted at one end called the top of the stack.

© Oxford University Press 2013. All rights reserved.


STACK

A stack is an ordered collection of elements into


which new elements may be inserted and from
which elements may be deleted at one end.
the common operations associated with a stack
are push and pop.
 Inserting an item in a stack is called pushing it
onto the stack.
 Removing an item from a stack is called popping
the stack.
 Items are added and removed from only one
designated end called the top of the stack.

© Oxford University Press 2013. All rights reserved.


STACK

Two important preconditions associated with the


push and pop operations are overflow and
underflow, respectively.
 Whilst a stack is conceptually unbounded,
eventually successive pushes will cause the
stack to overflow.
 Trying to pop an element off an empty stack is
called underflow.
Other operations on stacks include the following:
 Size returns the number of elements present in
the stack.
 Peek operation on stack returns the topmost
element without removing it.
© Oxford University Press 2013. All rights reserved.
AN EXAMPLE:
Such a stack resembles a stack of trays in a
cafeteria, or a stack of boxes.
 Only the top tray can be removed from the stack and it is
the last one that was added to the stack.
 A tray can be removed only if there are some trays on the
stack, and a tray can be added only if there is enough
room to hold more trays.
 The stack is based on the LIFO (Last In First Out) principle
as the last element inserted will be on the top of the
stack.
 Since deletion is done from the same end, the last
element inserted is the first element to be deleted

© Oxford University Press 2013. All rights reserved.


IMPLEMENTATION OF STACK
 A stack can be implemented in either of the following two
ways:
 Statically using arrays
 Dynamically by linked lists
 Array Implementation of Stack : A stack is represented
as a structure with two members:
 an array to hold data items,
 an integer variable showing the top of the stack.
İt is the array index of the element at top of stack .Such a
structure can be represented as follows:
#defi ne SIZE 100
struct stack
{
int list[SIZE];
int top;
};
© Oxford University Press 2013. All rights reserved.
PUSH OPERATION

push operation would be as follows:


void push(struct stack *sp,int x)
{
if(sp->top == SIZE-1)
{
printf(“\n OVERFLOW”);
return;
}
sp->list[++sp->top] = x;
return;
}

© Oxford University Press 2013. All rights reserved.


POP OPERATION

pop operation would be as follows:


int pop(struct stack *sp)
{
/* Check for stack underfl ow */
if(sp->top == -1)
{
printf(“\nSTACK IS EMPTY i,e UNDERFLOW”);
return (-1);
}
return(sp->list[sp->top--]);
}
The peek operation is implemented as n =
list[top] and return n

© Oxford University Press 2013. All rights reserved.


REPRESENTATION OF PUSH AND POP
OPERATION ONTO STACK

© Oxford University Press 2013. All rights reserved.


PEEK OPERATION

The c function for peek operation is given


below.
int peek(struct stack p)
{
int n;
if(p.top == -1)
{
printf(“\nSTACK IS EMPTY i,e UNDERFLOW”);
return (-1);
}
n = p.list[p.top];
return n;
}

© Oxford University Press 2013. All rights reserved.


SIZE OPERATION

C function for implementing the size operation


could be as written below.
int size(struct stack p)
{
int n;
if(p.top == -1)
return 0;
else
return(p.top + 1);
}

© Oxford University Press 2013. All rights reserved.


LINKED LIST IMPLEMENTATION OF
STACK
Implementing stacks as linked lists provides a
solution to the problem of dynamically growing
stacks, as a linked list is a dynamic data structure.
This provides better use of memory.
A stack can be implemented using pointers, as a
form of a linked list.
Top is a pointer to the top of the list that is head.
When the top is NULL, the stack is empty.

© Oxford University Press 2013. All rights reserved.


each data item of the stack is stored in a node, which
also holds a pointer to the next node on the list.
struct node
{
int item;
struct node *next;
};
Let top be a pointer pointing to the top node (lastly
pushed) of stack. It is declared as follows.
 struct node *top;
When stack is implemented in linked list, it will never
overflow until memory allocation fails. Initially top is
set to NULL that indicates the stack is empty.

© Oxford University Press 2013. All rights reserved.


EXAMPLE

The number 12 is to be pushed onto stack. After


pushing the value, the stack becomes as shown in
Fig.
Next 5 is pushed onto the stack [see Fig.]. When 7
is pushed, the stack can be represented as in Fig.
Now, if the stack is popped, the popped element
would be 7. The pointer top would point to the next
node, i.e., node containing the data 5. See Fig.
Again, if another pop operation is performed, then
stack is depicted in Fig.

© Oxford University Press 2013. All rights reserved.


FIGURE:EXAMPLE

© Oxford University Press 2013. All rights reserved.


DISCUSSION

Another important thing to be noted for the


implementation of push operation is that the new
element will be always added at the beginning of
the linked list and while popping
an element, it will be deleted from the same end,
i.e. from the beginning of the linked list.
There is no condition base for overflow, but if the
malloc() function returns NULL, i.e. no more
memory is available for allocation, then it is
assumed that the stack is full.

© Oxford University Press 2013. All rights reserved.


CONT.

All operations for the array-based and linked stack


implementations take constant time.
The only basis for comparison is the total space
(memory space) required.
The array-based stack must declare a fixed size
array initially, and some of that space is wasted
whenever the stack is not full.
The linked stack can shrink and grow, but requires
the overhead of an address field (here the field is
called as next) for every node.

© Oxford University Press 2013. All rights reserved.


APPLICATION OF STACK

The stack is a way of forming a data structure that


arranges data elements one above the other
resembling a stack of books and allows entry and
exit of data elements from the top of this
structure.
 This therefore uses the LIFO technique to store and
retrieve data elements.
 This way of storing and retrieving data elements is used in
a variety of applications.
 Some of these are discussed below.
Direct Applications
 There are applications where the stack data structure is
used directly. Some of these are mentioned in next slide.

© Oxford University Press 2013. All rights reserved.


DIRECT: APPLICATION OF STACK
Page-visited history in a Web browser The
web: browser keeps a record of the web-pages
visited by the user over a period of time.
Undo sequence in a text editor : This is similar
to the previous application.
Resolving function call This again is
another : application where one function calls a
second function and so on.
Simulating recursion : Recursive functions are
handled by runtime stack.
 In the recursion, two recursive calls are regarded as being
different so that it does not mix the data areas for one call
with another where one is called from within the other.

© Oxford University Press 2013. All rights reserved.


DIRECT: APPLICATION OF STACK

Evaluating expression : Another application of


the stack is in expression evaluation.
 A complex assignment statement such as a = b + c*d/e–f
may be interpreted in many different ways.
 In infix notation, the binary operator comes in between the
operands.
 evaluation of a postfix expression is possible using a stack-
based algorithm.
 This technique is also implemented in parsing. Parsing is
the second phase of program compilation

© Oxford University Press 2013. All rights reserved.


INDIRECT: APPLICATION OF STACK
Indirect Applications
 Auxiliary data structure for algorithms like
backtracking algorithm : A backtracking algorithm
systematically considers all possible outcomes for each
decision and performs much better than exhaustive
search.
 To explore a solution space of the problem, depth-search
traversal of the solution space can be performed.
 This depth-first traversal uses stack data structure.
 The backtracking algorithm is often used in optimization
and in games.

© Oxford University Press 2013. All rights reserved.


QUEUE

A queue is an ordered set of homogeneous elements in


which the items are added at one end (called the rear)
and are removed from the other end (called the front).
A queue is a First In First Out (FIFO) data structure
where the first element, which is inserted into the
queue, will be the first one to be removed.
Implementation of Queue
 Array Implementation of Queue: A queue may be
represented as a structure containing an array list and
two variables namely front and rear to denote the present
position of its front and rear element. A queue may be
defined as given below:
struct Queue
{
int list[MAX_SIZE];
int rear, front;
};
© Oxford University Press 2013. All rights reserved.
COMMON OPERATIONS ON A QUEUE

The common operations on a queue include the


following:
 Initialize This operation creates a new empty queue.
This operation must be done in order to make the queue
logically accessible.
 Enqueue This operation inserts an element into the
queue provided the queue is not full. Whilst a queue is
conceptually unbounded, eventually successive enqueues
(without dequeues) will cause the queue to overflow as the
queue is practically bounded.
 Dequeue This operation removes and then returns
the element at the front of the queue. The precondition for
this operation is that the queue must not be empty. Trying
to dequeue an item off an empty queue causes an
underflow.

© Oxford University Press 2013. All rights reserved.


ENQUEUE OPERATION

© Oxford University Press 2013. All rights reserved.


DEQUEUE OPERATION

© Oxford University Press 2013. All rights reserved.


LINKED LIST IMPLEMENTATION
OF QUEUE
The queue can be implemented as a linked list with
one external pointer to the front of the queue and a
second external pointer to the rear (back) of the
queue.
 Each element of the queue can be represented as follows:
struct node
{
int data;
struct node *next;
};
 Let us have two pointers, front to the first element of the list
and rear to the last element of the list.
 Both pointers must be of type struct node.
 To initialize the queue to empty, the front and rear pointers
are set to NULL.
© Oxford University Press 2013. All rights reserved.
CONT.

 To implement the enqueue operation using a function, the


memory should be allocated trough malloc() function and the
data has to be set with suitable value.
 If the queue is empty, both the front and rear pointer should
be set to point to the new node.
 If the malloc() function is unable to allocate memory for
the node, then the ‘overflow’ error would have to be
flashed.

© Oxford University Press 2013. All rights reserved.


CONT.
 To implement dequeue operation, the node pointed by the
pointer front will have to be deleted using free() function
and front should point to the next node of the linked list.
 Any attempt to dequeue an element from the empty
queue would cause the underflow error.
 The queue is empty when the front is NULL.

© Oxford University Press 2013. All rights reserved.


OTHER VARIATIONS OF QUEUE

Priority queue
Priority queue is a special type of queue in which
items can be inserted or deleted based on the
priority. Different types of priority queues are:
 1. Ascending priority queue
 2. Descending priority queue
In an ascending priority queue, elements can be
inserted in any order.
 But while deleting an element from the queue, remove
only the smallest element first.
 In a descending priority queue, elements can be inserted
in any order but while deleting, the largest element is
deleted first.
 It is to be noted that for elements of same priority, the
FIFO order is used.

© Oxford University Press 2013. All rights reserved.


OTHER VARIATIONS OF QUEUE
Double Ended Queue or Deque
A deque is a homogeneous list in which
elements can be inserted or deleted from
both the ends. i.e.;
 we can add a new element at the rear or front
end and also we can remove an element from
both front and rear end.
 Hence it is called as double ended queue.
There are two types of deque depending upon
the restriction to perform insertion or deletion
operations at the two ends. They are:
 1. Input restricted deque
 2. Output restricted deque

© Oxford University Press 2013. All rights reserved.


DOUBLE ENDED QUEUE OR DEQUE

An input restricted deque allows insertion at only


one end (rear end), but allows deletion at both the
ends, rear and front end of the lists.
 An output-restricted deque allows deletion at only one end
(front end), but allows insertion at both ends (rear and front
ends) of the lists.
The possible operations performed on a deque are:
 1. Add an element at the rear end
 2. Add an element at the front end
 3. Delete an element from the front end
 4. Delete an element from the rear end

© Oxford University Press 2013. All rights reserved.


APPLICATIONS OF QUEUE

Direct Application
 Print queue: The most common application of a queue is
the print queue. When multiple print jobs are sent to a
printer, each printing job is inserted at the rear of the
queue in the order it was sent.
 Ready queue: Processes waiting to be executed by a
CPU are usually in the form of a queue. These may also
take the form of a priority queue.
 For example, in a multi-user system, there will be
several programs competing for the central processor at
one time.

© Oxford University Press 2013. All rights reserved.


APPLICATIONS OF QUEUE

Direct Application
 Message queue: In a computer network, messages from
one computer to another are generally created
asynchronously.
 Any type of stream throughput of I/O will use a queue.
Scheduling of jobs within a time-sharing system is another
application of queues.
Auxiliary data structure in algorithms
 Queues are used in finding the shortest path in a graph
 Queues can be used for Discrete Event Simulation

© Oxford University Press 2013. All rights reserved.


TREE

Trees are useful for organizing data in a manner


that makes it efficient to retrieve it.
 A tree in which each node can have a maximum of two
children is known as a binary tree.
 There are three commonly used traversals for a binary
tree—Preorder, Inorder, and Postorder.
 There are several variations of binary trees which are
useful models in many different situations.
 One of the most familiar uses of tree structures is to
organize file systems.
 Trees are also used to organize information in database
systems and to represent the syntactic structure of source
programs in compilers.

© Oxford University Press 2013. All rights reserved.


TREE
A tree is a set of points and lines.
 The points are called nodes and the lines are called edges
as is depicted in Fig.
 The edges connect two distinct nodes.
The tree becomes a data structure when the
nodes hold some data and the links between the
nodes are established with the use of pointers.
 The diagram in Fig. is an example of a tree.

© Oxford University Press 2013. All rights reserved.


TREE

The non-recursive definition basically considers a


tree as a special case of a more general data
structure, the graph.
The recursive definition of a tree is given below. A
tree is a set of one or more nodes T such that:
 There is a specially designated node called a root

 The remaining nodes are partitioned into n disjointed set


of nodes T1, T2,…,Tn, each of which is a tree.

© Oxford University Press 2013. All rights reserved.


TREE

primary properties:
 In a tree structure, one node is distinct and is called the
root. The root is the top-most node from which edges
originate, but no edges terminate.
 Nodes may be categorized as a parent or a child or a leaf.
 All nodes are related to the root node.
The different types of trees structures in
decreasing order of generality are:
 Trees
 Rooted trees
 Ordered trees
 M-ary trees and binary trees

© Oxford University Press 2013. All rights reserved.


SOME BASIC TREE TERMINOLOGY

Tree :A tree is a non-empty collection of nodes (or


vertices) and edges (or lines) that satisfies the
condition that a unique node exists at the topmost
level which may or may not have a node(s) connected
in a hierarchical order below it with edges.
Node: Each element of a tree is called a node of the
tree.
Edge : An edge is a connecting link between two
nodes (or vertices).
Leaf: It is a node that does not have any child node of
its own. It means that such a node is a special child
node that has a parent but does not have any node
which is a child to it.

© Oxford University Press 2013. All rights reserved.


SOME BASIC TREE TERMINOLOGY
Depth: The depth of a tree is defined as the
maximum value of the level of the node of the
tree considering the root node as the datum node.
 It may be noted that the root of a tree is said to be at
depth 0, and every other nodes is said to have a depth
which is the number of links from the root to the node.
 The depth of the tree as a whole is the maximum depth of
all nodes within the tree.
Descendants: The descendants of a node are all
the nodes that are on some path from the node to
any leaf.
Ancestors: The ancestors of a node are all the
nodes that are on the path from the node to the
root.
© Oxford University Press 2013. All rights reserved.
SOME BASIC TREE TERMINOLOGY
Sibling: Nodes with a common parent are called
siblings.

Degree: The degree of a node of a tree is the number


of sub-trees having this node as a root. In other words,
the degree is the number of descendants of a node. If
the degree is zero, it is called a terminal or leaf node.
 The degree of a tree is defined as the maximum of degree of
the nodes of the tree, that is, degree of tree = max (degree
(node i) for i = 1 to n)
External node : A leaf or external node is any node
that has no non-empty children.
Internal node: An internal node is any node that has
at least one non-empty child.

© Oxford University Press 2013. All rights reserved.


SOME BASIC TREE TERMINOLOGY

Root: It is the topmost node in a tree and all other


nodes branch off from this node.
Level The level of a node in a binary tree:
 the root of the tree has level 0
 the level of any other node in the tree is one more than the
level of its parent.
Path: A path in a tree is a list of distinct vertices in
which successive vertices are connected by edges.
Height: It is defined to be the length of the longest
path from the root to a leaf in that tree (including the
path to root).

© Oxford University Press 2013. All rights reserved.


BINARY TREE

 A tree in which each node can have maximum of two children


is known as a binary tree.
 Hence, in such a tree, each node can have no child, one child, or
two children.
 The binary tree has a left child and a right child.
 The mathematical definition of a binary tree is given below.
 A binary tree is a finite set of elements that is either empty or is
partitioned into three disjoint subsets.
 The first subset contains a single element called the root of the
tree.
 The other two subsets are themselves binary trees called the left
and right sub-trees. Each element of a binary tree is called a node
of the tree.

© Oxford University Press 2013. All rights reserved.


BINARY TREE
A binary tree is known as a full binary tree when,
 Each non leaf node has exactly two child nodes.
 All leaf nodes have identical path length.
 All possible node slots are occupied.
A complete binary tree is a special case, in which
all the levels, except perhaps the last, are full;
while on the last level, any missing nodes are to
the right of all the nodes that are present.
 Figure depicts an example of a complete binary tree.

© Oxford University Press 2013. All rights reserved.


COUNTING BINARY TREES

 Let bn denote the number of binary trees on n vertices.


 We define, for convenience, b0 = 1.
 Clearly, b1 = 1. For n > 1, a binary tree on n vertices has a left
subtree on, say, j vertices and a right subtree on n–1–j vertices.
 To count the number of trees, we would add up the possibilities
for each value of j, thus:
 bn = b0bn–1 + b1bn–2 + ... + bn–1b0
 This recursion relation is known as the Catalan recursion
and the numbers bn are known as the Catalan numbers.
 The Catalan numbers solve a large number of different
looking counting problems.
 The number bn of different binary trees on n vertices is given by

© Oxford University Press 2013. All rights reserved.


COUNTING BINARY TREES

Therefore, the number of possible binary trees in


n nodes is:
 1/n * C(2n, n) = 1/(n+1) * (2n)!/(n!n!).
 An almost complete binary tree is a tree in which for a
right child, there is always a left child, but for a left child
there may not be a right child.
More strictly, to be an almost complete binary
tree,
 1. all leaves are at level d or d – 1.
 2. L if a node is having right descendant at level d, then
all leaves in its left subtree will be at level d.
If every non-leaf node in a binary tree has non-
empty left and right subtrees , the tree is termed
as a strictly binary tree.
 That is, it is a binary tree where every non-leaf node must
have both left and right child.
© Oxford University Press 2013. All rights reserved.
TRAVERSALS OF A BINARY TREE

Traversing of a tree basically entails visiting all the


nodes of the binary tree.
 In the traversal technique, each node in the tree is
processed or visited once, systematically one after the
other.
 Processing may include just displaying the contents of the
node or assist in some other operation.
There are three commonly used traversals for a
binary tree, (a)preorder, (b)inorder, and
(c)postorder.

© Oxford University Press 2013. All rights reserved.


TRAVERSALS OF A BINARY TREE
Tree is a non-linear data structure.
 The maximum level of any leaf in a binary tree is called
the depth of the tree.
 Other than the root node, the level of each node is one
more than the level of its parent node.
 A complete binary tree is necessarily a strictly binary tree
but not vice versa.
 At any level k, there are 2k nodes at that level in a
complete binary tree.
 The total number of nodes in a complete binary tree of
depth d is (2d+1 – 1).
 In a complete binary tree, there are 2d leaf nodes and (2d
– 1) non-leaf nodes.

© Oxford University Press 2013. All rights reserved.


TRAVERSALS OF A BINARY TREE
Inorder traversal:
 1. Traverse the left sub-tree in inorder
 2. Visit the root
 3. Traverse the right sub-tree in inorder
In short LNR where L, N, R stand for Left, Node, and
Right, respectively.
Preorder traversal:
 1. Visit the root
 2. Traverse the left sub-tree in preorder
 3. Traverse the right sub-tree in preorder
In short NLR where L, N, R stand for Left, Node, and
Right, respectively.
Postorder traversal:
 1. Traverse the left-sub tree in postorder
 2. Traverse the right-sub tree in postorder
 3. Visit the root
In short LRN where L, N, R stand for Left, Node, and
Right, respectively.
© Oxford University Press 2013. All rights reserved.
KINDS OF BINARY TREES
There are several variations of binary trees which
are useful models in many different situations.
Three of the more common ones are:
 Binary search tree
 Expression tree
 Heap
A binary search tree is a binary tree in which
each node contains a key, all keys are unique, and
for any node the keys in its left sub-tree are less
than the key in the node itself and the keys in its
right sub-tree are greater than the key in the node
itself.

© Oxford University Press 2013. All rights reserved.


KINDS OF BINARY TREES

An expression tree is a binary tree that stores an


expression such as an arithmetic expression in
such a way that each leaf node contains an
operand of the expression, & each interior node
contains an operator of the expression.

 A heap is a complete binary tree, each of whose nodes


contains a key which is greater than or equal to the key in
each of its children. Actually, this is technically a max heap.
 A min heap is a complete binary tree, each of whose nodes
contains a key which is less than or equal to the key in each
of its children. The following tree is an example of a heap.

© Oxford University Press 2013. All rights reserved.


BINARY SEARCH TREE

In a binary tree, if the values in its nodes are


arranged in a specific order, with all the values
stored in the nodes smaller than that of the root
stored in the left sub-tree and all nodes with
values greater than that of the root stored as the
right sub-tree, it represents a sorted list.
 The reason for such ordering is that the complexity of
searching an element reduces considerably,
 as one has to check only one node at each level of the
height,
 so complexity is given by the height of the tree, and the
height of the tree is much less than the total number of
elements.
 When a binary tree has ‘m’ levels counting down 0,1,2,….,
m, the tree can have a maximum of (2m+1 –1) nodes.
© Oxford University Press 2013. All rights reserved.
CONSTRUCTING A BINARY SEARCH TREE

Generally we say that once the root is created, if


the value is less, it should go to the left sub-tree,
otherwise to the right sub-tree.
Actually with the value to be searched, the current
node in the tree should inform us, in some way,
whether the value should be searched in the left
sub-tree or right sub-tree of the node.
Example: Construct a binary search tree from the
following set of values: 9, 5, 6, 12, 10, 17, 3, 11,
4.
 Given in next slide .

© Oxford University Press 2013. All rights reserved.


DIFFERENT STAGES OF CONSTRUCTING
THE BST FOR THE GIVEN DATA
SEQUENCE

© Oxford University Press 2013. All rights reserved.


CONT.

© Oxford University Press 2013. All rights reserved.


IMPLEMENTATION OF A BINARY SEARCH
TREE
As is case of stacks and queues, a binary search
tree can be implemented using arrays as well as
using linked lists.
Implementation of a binary search tree using
array: As trees are not a linear data structure,
representing a tree using arrays requires a proper
mapping from the tree structure into a linear
organization.
 In case of binary search tree, each node may have at most
two successors.
 Consider the tree in Fig.

© Oxford University Press 2013. All rights reserved.


IMPLEMENTATION OF A BINARY
SEARCH TREE
 The nodes in the tree have been numbered
consecutively, starting from 0 (root), 1 and 2 have
been assigned to the children of the root, 3... 6 have
been used for the grandchildren of the root and so
on.
 the above numbering scheme needs to be
considered, and if a node is assigned node j, simply
that node has to be stored in the location a[j] of the
array.

© Oxford University Press 2013. All rights reserved.


IMPLEMENTATION OF A BINARY
SEARCH TREE
 Thus, if one is positioned in a node which is in position
I of the array, then we can easily identify:
 the left child will be in position 2 × i + 1,
 the right child will be in position 2 × i + 2,
 the root is in position 0.
 We assume that if a node does not exist, then the
corresponding entry in the array is filled with a default
value say –1.

© Oxford University Press 2013. All rights reserved.


IMPLEMENTATION OF A BST USING
LINKED LIST THE STRUCTURE

used for representing the node for a binary search


tree with three fields: a data value, a left link and a
right link is shown below:
typedef struct node
{
int data;
struct node *left;
struct node *right;
} NODE;
typedef NODE *NODEPTR;

© Oxford University Press 2013. All rights reserved.


IMPLEMENTATION OF A BST USING
LINKED LIST THE STRUCTURE

Here the data field may be of any type and size,


and two pointers are used to point to the left child
and right child respectively.
 This structure is again dynamic in nature and there is no
limitation on the number of nodes, and one can go on
building the tree in any form until malloc() fails.
 When the tree is not required, one can free all the nodes
so that the memory can be utilized for some other
process.
 The ‘root’ pointer points to the topmost node in the tree.
 A null pointer represents a binary tree with no elements,
the empty tree.
 The linked representation of a binary search tree is shown
in Fig. 12.20.
© Oxford University Press 2013. All rights reserved.
CONT.
The more complex operation on binary search trees is
the deletion of a node.
Removing a node from a BST is fairly straightforward,
with four cases to be considered:
 1. the value to be removed is a leaf node; or
 2. the value to be removed has a right sub-tree, but no left
sub-tree; or
 3. the value to be removed has a left sub-tree, but no right
sub-tree; or
 4. the value to be removed has both a left and a right sub-tree.
There is also an implicit fifth case whereby the node to
be removed is the only node in the tree.
 This case is already covered by the first, but should be noted
as a possibility nonetheless.

© Oxford University Press 2013. All rights reserved.


APPLICATION OF TREE

 Trees are used to help analyze electrical circuits and


to represent the structure of mathematical formulas.
 One of the most familiar uses of tree structures is to
organize file systems.
 Files are kept in directories (which are also
sometimes called folders) that are defined
recursively as sequences of directories and files.

© Oxford University Press 2013. All rights reserved.


APPLICATION OF TREE

 The in-order traversal of the binary tree for an


arithmetic expression produces the infix form of the
expression, while the pre-order and post-order
traversal lead to the prefix and postfix (reverse Polish)
forms of the expression respectively.
 Trees are also used to organize information in
database systems.
 Apart from these, trees can be used in a wide variety
of applications, which includes set representations,
decision making, game trees, etc.

© Oxford University Press 2013. All rights reserved.

You might also like