0% found this document useful (0 votes)
6 views108 pages

Adt Final

The document discusses recursion, explaining it as a process where a function calls itself to simplify problems into subproblems, exemplified by the factorial function. It also covers applications of recursion such as the Towers of Hanoi and Koch snowflake, as well as abstract data types (ADTs) and linked lists. Additionally, it describes tree structures, their traversals, and binary search trees, along with operations for insertion and deletion.

Uploaded by

jaishekhwat336
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)
6 views108 pages

Adt Final

The document discusses recursion, explaining it as a process where a function calls itself to simplify problems into subproblems, exemplified by the factorial function. It also covers applications of recursion such as the Towers of Hanoi and Koch snowflake, as well as abstract data types (ADTs) and linked lists. Additionally, it describes tree structures, their traversals, and binary search trees, along with operations for insertion and deletion.

Uploaded by

jaishekhwat336
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/ 108

ABSTRACT DATA

STRUCTURE
TOPIC 5
RECURSION

 The process in which a function calls itself directly or indirectly is


called recursion and the corresponding function is called as recursive function.
 Recursion is a common method of simplifying a problem into subproblems of same
type. This is called divide and conquer technique. A basic example of recursion is
factorial function.
 int factorial(int n){
if(n==0)
return 1;
else
return (n* factorial(n-1));
 }
 Fact(4) = 5 * fact(4)
 Fact(4) = 4 * fact(3)
 Fact(3)= 3* fact(2)
 Fact(2)= 2* fact(1)
 Fact(1)= 1 * fact(0)

 Start solving
 fact(1)=1*1=1 (place this value in fact(2))
 Fact(2)= 2* 1=2
 Fact(3) = 3 * 2 =6
 Fact(4) = 4* 6= 24
 Fact(5) = 5* 24 =120
 public class JavaApplication1 {
 /**
 * @param args the command line arguments
 */
 public static void main(String[] args) {

 int f= this.factorial(5);
 System.out.println("factorial= "+f);
 }

 int factorial(int n){


 if(n==0)
 return 1;
 else
 return (n* factorial(n-1));

 }

 }
WHY RECURSION?

 It sometimes makes your code much simpler.


 People use recursion only when it is very complex to write iterative code.
 For example, tree traversal techniques like preorder, postorder can be made
both iterative and recursive. But usually we use recursive because of its
simplicity
APPLICATIONS OF RECURSION

 TOWERS OF HANOI
 SNOWFLAKES
TOWERS OF HANOI

 Its a puzzle
 Consists three rods and number of discs
 Goal of puzzle
 Move the stacks of discs from the first rod to third with following rules:
 Disc may not be placed on top of smaller one
 Only one disc may move on every move
 Only top disc will move from the rod
 Third rod is for temporary storage
Tower of Hanoi(cont..)

 https://youtu.be/fffbT41IuB4
moveDisc(n,from,dest,aux)
START

DECLARE n TRUE
n=1 ?

FLASE
INPUT n
moveDisc(n-1,from,dest,aux)

Move disc n from “from” to


moveDisc(n,A,B,C)
“dest”

moveDisc(n-1,aux,from,dest)
STOP
Move disc 1 from
“from” to “dest”
RETURN
SNOWFLAKES

 The Koch snowflake (also known as the Koch curve, Koch star, or Koch island)
is a mathematical curve and one of the earliest fractal curves to have been
described.
 It is based on the Koch curve, which appeared in a 1904 paper titled “On a
continuous curve without tangents, constructible from elementary geometry”
by the Swedish mathematician Helge von Koch.
 The progression for the area of the snowflake converges to 8/5 times the area
of the original triangle,
 while the progression for the snowflake’s perimeter diverges to infinity.
Consequently, the snowflake has a finite area bounded by an infinitely long
line.
Construction
Step1:
Draw an equilateral triangle.
It’s best if the length of the sides are divisible by 3, because of the nature of this fractal. This will become clear in the next few steps.
Step2:
Divide each side in three equal parts. This is why it is
handy to have the sides divisible by three.
Step3:
Draw an equilateral triangle on each middle part. Measure the length of the middle third
to know the length of the sides of these new triangles.
Step4:
Divide each outer side into thirds. You can see the 2nd generation of triangles covers a bit
of the first. These three line segments shouldn’t be parted in three.
Draw an equilateral triangle on each middle part.
•Note how you draw each next generation of parts that are one 3rd of the mast one.
 https://youtu.be/xlZHY0srIew
Abstract Data Type(ADT)

 An abstract data type or ADT (sometimes called an abstract data type) is a


mathematical model of a data structure.
 It describes a container which holds a finite number of objects where the
objects may be associated through a given binary relationship.
 ADT is a data type, where only behavior is defined but not implementation.
 Some example of Abstract Data Structure are :
 Linked List.
 Tree.
 Graph.
 Stack, Queue etc.
Static Data structure vs Dynamic Data
Structure
 Static Data structure has fixed memory size whereas in Dynamic Data
Structure, the size can be randomly updated during run time
 Dynamic Data Structure may be considered efficient with respect to memory
complexity of the code.
 Unlike static data structures, dynamic data structures are flexible.
Linked List

 A linked list is a linear data structure where each element is a separate


object.
 Each element (we will call it a node) of a list is comprising of two items -
the data and a reference to the next node.
 The last node has a reference to null.
 The entry point into a linked list is called the head of the list.
Basic Operations

Following are the basic operations supported by a list.

 Insertion − Adds an element at the beginning of the list,after an element,at end

 Deletion − Deletes an element at the beginning of the list list,after an element,at end

 Display − Displays the complete list.

 Search − Searches an element using the given key.

 Delete − Deletes an element using the given key.


Insertion Operation
 Adding a new node in linked list is a more than one step activity. We shall
learn this with diagrams here.
 First, create a node using the same structure and find the location where it
has to be insert
 Imagine that we are inserting a node B (NewNode), between A (LeftNode)
and C (RightNode). Then point B.next to C −

Similar steps should be taken if the node is being inserted at the beginning of
the list. While inserting it at the end, the second last node of the list should point
to the new node and the new node will point to NULL.
Deletion Operation
 Deletion is also a more than one step process. We shall learn with pictorial
representation. First, locate the target node to be removed, by using
searching algorithms

The left (previous) node of the target node now should


point to the next node of the target node −

leftNode.next -> targetNode.next


Types of linked list

Following are the various types of linked list.


 Simple Linked List − Item navigation is forward only.

 Doubly Linked List − Items can be navigated forward and backward.


 Circular Linked List − Last item contains link of the first element as next and the first
element has a link to the last element as previous.in both directions.
 Singly Linked List as Circular
 In singly linked list, the next pointer of the last node points to the first node.

 Doubly Linked List as Circular


 In doubly linked list, the next pointer of the last node points to the first node and the
previous pointer of the first node points to the last node making the circular
JETS
void add(int index, Object element):

Output:
LinkedList: [Hi, I, Love, java]
LinkedList: [Hi, Element, I, Love, java]
Object get(int index)
Identify the components of a node in a doubly linked list.
TREE
Tree
 Tree is a hierarchical data structure which stores the information naturally in
the form of hierarchy style.
 Tree is one of the most powerful and advanced data structures.
 It is a non-linear data structure compared to arrays, linked lists, stack and
queue. It represents the nodes connected by edges
Important Terms
Following are the important terms with respect to tree.
•Path − Path refers to the sequence of nodes along the edges of a tree.
•Root − The node at the top of the tree is called root. There is only one root per
tree and one path from the root node to any node.
•Parent − Any node except the root node has one edge upward to a node called
parent.
•Child − The node below a given node connected by its edge downward is called
its child node.
•Leaf − The node which does not have any child node is called the leaf node.
•Subtree − Subtree represents the descendants of a node.
•Visiting − Visiting refers to checking the value of a node when control is on the
node.
•Traversing − Traversing means passing through nodes in a specific order.
•Levels − Level of a node represents the generation of a node. If the root node is
at level 0, then its next child node is at level 1, its grandchild is at level 2, and so
on.
•keys − Key represents a value of a node based on which a search operation is to
be carried out for a node.
Binary Tree Data Structure
 A tree whose elements have at most 2 children is called a binary tree.
 Since each element in a binary tree can have only 2 children, we typically
name them the left and right child.
Tree Traversals (Inorder, Preorder and
Postorder)

 Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which
have only one logical way to traverse them, trees can be traversed in
different ways.
 Following are the generally used ways for traversing trees.
 Depth First Traversals:
(a) Inorder (Left, Root, Right) : 4 2 5 1 3
(b) Preorder (Root, Left, Right) : 1 2 4 5 3
(c) Postorder (Left, Right, Root) : 4 5 2 3 1
 Breadth First or Level Order Traversal : 1 2 3 4 5
Inorder Traversal
Algorithm Inorder(tree)
1. Traverse the left subtree, i.e., call Inorder(left-subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right-subtree)

If a binary tree is traversed in-order, the output will


produce sorted key values in an ascending order.

D→B→E→A→F→C→G
Preorder Traversal

1.Visit the root.


2.Traverse the left subtree, i.e., call Preorder(left-subtree)
3.Traverse the right subtree, i.e., call Preorder(right-subtree)

the root node is visited first, then the left subtree and
finally the right subtree.

A→B→D→E→C→F→G
Postorder Traversal

1.Traverse the left subtree, i.e., call Postorder(left-subtree)


2.Traverse the right subtree, i.e., call Postorder(right-subtree)
3.Visit the root.

First we traverse the left subtree, then the right subtree


and finally the root node.

D→E→B→F→G→C→A
Binary Search Tree Representation

 Binary Search tree exhibits a special behavior. A node's left child must have a
value less than its parent's value and the node's right child must have a value
greater than its parent value.

Search Operation (use of in order traversal)


Whenever an element is to be searched, start searching
from the root node. Then if the data is less than the key
value, search for the element in the left subtree.
Otherwise, search for the element in the right subtree
Steps to add new node in a BST

1. If tree is empty,insert new node as a root


2. If BST is not empty,
1. If the key of the new node is smaller than parent’s node key then connect it as
the parent’s left hand child
2. If the key of the new node is greater than parent’s node key then connect it as
the parent’s right hand child

Note: in case of duplicasy insert a new node with a duplicate key as the right hand
child of the node with the same key
Steps to delete a node from BST

 If node to be deleted has no children: it just be deleted

 The node (X) to be deleted has one child: connect the parent of X with the child
of X.
 The node (X) to be deleted has two children:
 replace the X with the node that has the largest value in its left hand subtree (inorder
successor),
OR
 Replace the X with the smallest value in its right hand subtree (inorder predecessor)

Refer book page: 47 to 50


Book page 46
Read “ searching for a particular data item in a BST”
How to find minimum and maximum value in BST
Read balanced tree
Homework book page no 51
Stack and QUEUE
QUEUE
Circular Queue
Infix : An expression is called the Infix expression if the operator appears in between the
operands in the expression. Simply of the form (operand1 operator operand2).

Example : (A+B) * (C-D)

Prefix : An expression is called the prefix expression if the operator appears in the
expression before the operands. Simply of the form (operator operand1 operand2).

Example : *+AB-CD (Infix : (A+B) * (C-D) )


Infix to postfix conversion
1. Scan the Infix string from left to right.
2. Initialize an empty stack.
3. If the scanned character is an operand, add it to the Postfix string.

4.
If the scanned character is an operator and if the stack is empty push the character
to stack.
If the scanned character is an Operator and the stack is not empty, compare the
5. precedence of the character with the element on top of the stack.
If the scanned character is “)” pop all the operators till “(“
If top Stack has higher precedence over the scanned character pop the stack else
6. push the scanned character to stack. Repeat this step until the stack is not empty
and top Stack has precedence over the character.
7. Repeat 4 and 5 steps till all the characters are scanned.

8.
After all characters are scanned, we have to add any character that the stack may
have to the Postfix string.
9. If stack is not empty add top Stack to Postfix string and Pop the stack.
10. Repeat this step as long as stack is not empty.
Infix to prefix conversion
Step 1: Reverse the infix expression i.e A+B*C will become C*B+A. Note while reversing each
‘(‘ will become ‘)’ and each ‘)’ becomes ‘(‘.

Step 2: Obtain the postfix expression of the modified expression i.e CB*A+.

Step 3: Reverse the postfix expression. Hence in our example prefix is +A*BC.
(d)

You might also like