DAA Introduction - in Chapter - I and lecture

Ranjithsingh20 25 views 41 slides Sep 15, 2025
Slide 1
Slide 1 of 41
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41

About This Presentation

DAA Introduction


Slide Content

Unit - 1Unit - 1
Design and Analysis of AlgorithmDesign and Analysis of Algorithm
INTRODUCTIONINTRODUCTION
Dr. K. RANJITH SINGHDr. K. RANJITH SINGH
Assistant ProfessorAssistant Professor
Department of Computer ScienceDepartment of Computer Science
Karpagam Academy of Higher Education Karpagam Academy of Higher Education
(Deemed to be University)(Deemed to be University)
CoimbatoreCoimbatore

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-2
What is an algorithm?What is an algorithm?
An An algorithmalgorithm is a sequence of unambiguous instructions is a sequence of unambiguous instructions
for solving a problem, i.e., for obtaining a required for solving a problem, i.e., for obtaining a required
output for any output for any legitimatelegitimate input in a finite amount of input in a finite amount of
time.time.
“computer”
problem
algorithm
input output

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-3
AlgorithmAlgorithm

An An algorithmalgorithm is a sequence of unambiguous is a sequence of unambiguous
instructions for solving a problem, i.e., for instructions for solving a problem, i.e., for
obtaining a required output for any legitimate obtaining a required output for any legitimate
input in a finite amount of time.input in a finite amount of time.
• Can be represented various forms
• Unambiguity/clearness
• Effectiveness
• Finiteness/termination
• Correctness

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-4
Historical PerspectiveHistorical Perspective

Euclid’s algorithm for finding the greatest common divisorEuclid’s algorithm for finding the greatest common divisor

Muhammad ibn Musa al-Khwarizmi – 9Muhammad ibn Musa al-Khwarizmi – 9
thth
century century
mathematician mathematician
www.lib.virginia.edu/science/parshall/khwariz.htmlwww.lib.virginia.edu/science/parshall/khwariz.html

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-5
Notion of algorithm and problemNotion of algorithm and problem
“computer”
algorithmic solution
(different from a conventional solution)
problem
algorithm
input
(or instance)
output

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-6
Example of computational problem: sortingExample of computational problem: sorting

Statement of problem:Statement of problem:
•Input:Input: A sequence of A sequence of nn numbers <a numbers <a
11, ,
aa
22, …, a, …, a
nn>>
•Output:Output: A reordering of the input sequence <a A reordering of the input sequence <a
´´
11, ,
aa
´´
22, …, a, …, a
´´
nn> so that > so that
aa
´´
ii ≤≤ aa
´´
jj whenever whenever ii < < jj

Instance: The sequence <5, 3, 2, 8, 3>Instance: The sequence <5, 3, 2, 8, 3>
Algorithms:Algorithms:
•Selection sortSelection sort
•Insertion sortInsertion sort
•Merge sortMerge sort
•(many others)(many others)

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-7
Selection SortSelection Sort

Input: array Input: array a[1],…,a[n]a[1],…,a[n]

Output: array Output: array aa sorted in non-decreasing order sorted in non-decreasing order

Algorithm:Algorithm:
for i=1 to n
swap a[i] with smallest of a[i],…,a[n]
• Is this unambiguous? Effective?
• See also pseudocode, section 3.1

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-8
Some Well-known Computational ProblemsSome Well-known Computational Problems

SortingSorting

SearchingSearching

Shortest paths in a graphShortest paths in a graph

Minimum spanning treeMinimum spanning tree

Primality testingPrimality testing

Traveling salesman problemTraveling salesman problem

Knapsack problemKnapsack problem

ChessChess

Towers of HanoiTowers of Hanoi

Program terminationProgram termination
Some of these problems don’t have efficient algorithms,
or algorithms at all!

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-9
Basic Issues Related to AlgorithmsBasic Issues Related to Algorithms
How to design algorithmsHow to design algorithms

How to express algorithmsHow to express algorithms
Proving correctnessProving correctness
Efficiency (or complexity) analysisEfficiency (or complexity) analysis
•Theoretical analysisTheoretical analysis
•Empirical analysisEmpirical analysis
Optimality Optimality

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-10
Algorithm design strategiesAlgorithm design strategies

Brute forceBrute force

Divide and conquerDivide and conquer

Decrease and conquerDecrease and conquer

Transform and conquerTransform and conquer

Greedy approachGreedy approach

Dynamic programmingDynamic programming

Backtracking and branch-and-boundBacktracking and branch-and-bound

Space and time tradeoffsSpace and time tradeoffs

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-11
Analysis of AlgorithmsAnalysis of Algorithms

How good is the algorithm?How good is the algorithm?
•CorrectnessCorrectness
•Time efficiencyTime efficiency
•Space efficiencySpace efficiency

Does there exist a better algorithm?Does there exist a better algorithm?
•Lower boundsLower bounds
•OptimalityOptimality

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-12
What is an algorithm?What is an algorithm?

Recipe, process, method, technique, procedure, routine,… Recipe, process, method, technique, procedure, routine,…
with the following requirements:with the following requirements:
1.1.FinitenessFiniteness
terminates after a finite number of stepsterminates after a finite number of steps
2.2.DefinitenessDefiniteness
rigorously and unambiguously specifiedrigorously and unambiguously specified
3.3.Clearly specified inputClearly specified input
valid inputs are clearly specifiedvalid inputs are clearly specified
4.4.Clearly specified/expected outputClearly specified/expected output
can be proved to produce the correct output given a valid inputcan be proved to produce the correct output given a valid input
5.5.EffectivenessEffectiveness
steps are sufficiently simple and basicsteps are sufficiently simple and basic

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-13
Why study algorithms?Why study algorithms?

Theoretical importanceTheoretical importance
•the core of computer sciencethe core of computer science

Practical importancePractical importance
•A practitioner’s toolkit of known algorithmsA practitioner’s toolkit of known algorithms
•Framework for designing and analyzing algorithms for new Framework for designing and analyzing algorithms for new
problemsproblems
Example: Google’s PageRank Technology

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-14
Euclid’s AlgorithmEuclid’s Algorithm
Problem: Find gcd(Problem: Find gcd(m,nm,n), the greatest common divisor of two ), the greatest common divisor of two
nonnegative, not both zero integers nonnegative, not both zero integers m m and and nn
Examples: gcd(60,24) = 12, gcd(60,0) = 60, gcd(0,0) = ? Examples: gcd(60,24) = 12, gcd(60,0) = 60, gcd(0,0) = ?
Euclid’s algorithm is based on repeated application of equalityEuclid’s algorithm is based on repeated application of equality
gcd(gcd(m,nm,n) = gcd() = gcd(n, m n, m mod mod nn))
until the second number becomes 0, which makes the problemuntil the second number becomes 0, which makes the problem
trivial.trivial.
Example: gcd(60,24) = gcd(24,12) = gcd(12,0) = 12Example: gcd(60,24) = gcd(24,12) = gcd(12,0) = 12

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-15
Two descriptions of Euclid’s algorithmTwo descriptions of Euclid’s algorithm
Step 1 If Step 1 If nn = 0, return = 0, return mm and stop; otherwise go to Step 2 and stop; otherwise go to Step 2
Step 2 Step 2 Divide Divide mm by by n n and assign the value of the remainder toand assign the value of the remainder to r r
Step 3 Assign the value of Step 3 Assign the value of n n to to mm and the value of and the value of rr to to n. n. Go toGo to
Step 1. Step 1.

whilewhile nn ≠ 0 ≠ 0 do do
r ← m r ← m mod mod nn
m← n m← n
n ← rn ← r
returnreturn mm

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-16
Other methods for computing gcd(Other methods for computing gcd(m,nm,n))
Consecutive integer checking algorithmConsecutive integer checking algorithm
Step 1 Assign the value of min{Step 1 Assign the value of min{m,nm,n} to } to tt
Step 2 Step 2 Divide Divide mm by by t. t. If the remainder is 0, go to Step 3;If the remainder is 0, go to Step 3;
otherwise, go to Step 4 otherwise, go to Step 4
Step 3 Step 3 Divide Divide nn by by t. t. If the remainder is 0, return If the remainder is 0, return tt and stop; and stop;
otherwise, go to Step 4 otherwise, go to Step 4
Step 4 Decrease Step 4 Decrease t t by 1 and go to Step 2by 1 and go to Step 2
Is this slower than Euclid’s algorithm?
How much slower?
O(n), if n <= m , vs O(log n)

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-17
Other methods for gcd(Other methods for gcd(m,nm,n) [cont.]) [cont.]
Middle-school procedureMiddle-school procedure
Step 1 Find the prime factorization of Step 1 Find the prime factorization of mm
Step 2 Find the prime factorization of Step 2 Find the prime factorization of nn
Step 3 Find all the common prime factorsStep 3 Find all the common prime factors
Step 4 Compute the product of all the common prime factorsStep 4 Compute the product of all the common prime factors
and return it as gcd and return it as gcd(m,n(m,n))
Is this an algorithm?Is this an algorithm?
How efficient is it?How efficient is it?
Time complexity: O(sqrt(n))

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-18
Sieve of EratosthenesSieve of Eratosthenes
Input: Input: Integer Integer n n ≥≥ 2 2
Output: List of primes less than or equal to Output: List of primes less than or equal to nn
for for p p ← 2← 2 to to nn do do AA[[pp] ← ] ← pp
for for p p ← 2← 2 to to nn do do
if if AA[[pp] ]  0 // 0 //p p hasn’t been previously eliminated from the listhasn’t been previously eliminated from the list
j j ← ← pp** pp
while while j j ≤≤ n n dodo
AA[[jj] ] ← 0← 0 //mark element as eliminated//mark element as eliminated
j j ← ← jj + p+ p
Example: 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20Example: 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Time complexity: O(n)

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-19
Two main issues related to algorithmsTwo main issues related to algorithms

How to design algorithmsHow to design algorithms

How to analyze algorithm efficiencyHow to analyze algorithm efficiency

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-20
Algorithm design techniques/strategiesAlgorithm design techniques/strategies

Brute forceBrute force

Divide and conquerDivide and conquer

Decrease and conquerDecrease and conquer

Transform and conquerTransform and conquer

Space and time tradeoffsSpace and time tradeoffs

Greedy approachGreedy approach

Dynamic programmingDynamic programming

Iterative improvementIterative improvement

Backtracking Backtracking

Branch and boundBranch and bound

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-21
Analysis of algorithmsAnalysis of algorithms

How good is the algorithm?How good is the algorithm?
•time efficiencytime efficiency
•space efficiencyspace efficiency
•correctness ignored in this coursecorrectness ignored in this course

Does there exist a better algorithm?Does there exist a better algorithm?
•lower boundslower bounds
•optimalityoptimality

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-22
Important problem typesImportant problem types

sortingsorting

searchingsearching
string processingstring processing
graph problemsgraph problems

combinatorial problemscombinatorial problems

geometric problemsgeometric problems

numerical problemsnumerical problems

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-23
Sorting (I)Sorting (I)
Rearrange the items of a given list in ascending order.Rearrange the items of a given list in ascending order.
•Input: A sequence of n numbers <aInput: A sequence of n numbers <a
11, ,
aa
22, …, a, …, a
nn>>
•Output: A reordering <aOutput: A reordering <a
´´
11, ,
aa
´´
22, …, a, …, a
´´
nn> of the input sequence such that a> of the input sequence such that a
´´
11≤ ≤ aa
´´
2 2 ≤≤
… … ≤≤
aa
´´
n.n.
Why sorting?Why sorting?
•Help searchingHelp searching
•Algorithms often use sorting as a key subroutine.Algorithms often use sorting as a key subroutine.
Sorting keySorting key
•A specially chosen piece of information used to guide sorting. E.g., sort A specially chosen piece of information used to guide sorting. E.g., sort
student records by names.student records by names.

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-24
Sorting (II)Sorting (II)

Examples of sorting algorithmsExamples of sorting algorithms
•Selection sortSelection sort
•Bubble sortBubble sort
•Insertion sortInsertion sort
•Merge sortMerge sort
•Heap sort …Heap sort …

Evaluate sorting algorithm complexity: the number of key comparisons. Evaluate sorting algorithm complexity: the number of key comparisons.

Two propertiesTwo properties
•StabilityStability: A sorting algorithm is called stable if it preserves the relative order of : A sorting algorithm is called stable if it preserves the relative order of
any two equal elements in its input.any two equal elements in its input.
•In placeIn place : A sorting algorithm is in place if it does not require extra memory, : A sorting algorithm is in place if it does not require extra memory,
except, possibly for a few memory units.except, possibly for a few memory units.

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-25
Selection SortSelection Sort
AlgorithmAlgorithm SelectionSort(A[0..n-1])SelectionSort(A[0..n-1])
//The algorithm sorts a given array by selection sort//The algorithm sorts a given array by selection sort
//Input: An array A[0..n-1] of orderable elements//Input: An array A[0..n-1] of orderable elements
//Output: Array A[0..n-1] sorted in ascending order//Output: Array A[0..n-1] sorted in ascending order
for i for i  0 to n – 2 do 0 to n – 2 do
min min  i i
for j for j  i + 1 to n – 1 do i + 1 to n – 1 do
if A[j] < A[min] if A[j] < A[min]
min min  j j
swap A[i] and A[min]swap A[i] and A[min]

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-26
SearchingSearching

Find a given value, called a Find a given value, called a search keysearch key, in a given set., in a given set.

Examples of searching algorithmsExamples of searching algorithms
•Sequential searchSequential search
•Binary search …Binary search …
Input: sorted array a_i < … < a_j and key x;
m (i+j)/2;
while i < j and x != a_m do
if x < a_m then j  m-1
else i  m+1;
if x = a_m then output a_m;
Time: O(log n)

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-27
String ProcessingString Processing

A string is a sequence of characters from an alphabet. A string is a sequence of characters from an alphabet.

Text strings: letters, numbers, and special characters.Text strings: letters, numbers, and special characters.

String matching: searching for a given word/pattern in a String matching: searching for a given word/pattern in a
text.text.
Examples:
(i)searching for a word or phrase on WWW or in a
Word document
(ii)searching for a short read in the reference genomic
sequence

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-28
Graph ProblemsGraph Problems

Informal definitionInformal definition
•A graph is a collection of points called A graph is a collection of points called verticesvertices, some of , some of
which are connected by line segments called which are connected by line segments called edgesedges..
Modeling real-life problemsModeling real-life problems
•Modeling WWWModeling WWW
•Communication networksCommunication networks
•Project scheduling …Project scheduling …
Examples of graph algorithmsExamples of graph algorithms
•Graph traversal algorithmsGraph traversal algorithms
•Shortest-path algorithmsShortest-path algorithms
•Topological sortingTopological sorting

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-29
Fundamental data structuresFundamental data structures

listlist
•arrayarray
•linked listlinked list
•string string

stackstack

queuequeue

priority queue/heappriority queue/heap

graphgraph

tree and binary treetree and binary tree

set and dictionaryset and dictionary

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-30
Linear Data StructuresLinear Data Structures

ArraysArrays
•A sequence of n items of the same A sequence of n items of the same
data type that are stored data type that are stored
contiguously in computer memory contiguously in computer memory
and made accessible by specifying a and made accessible by specifying a
value of the array’s index.value of the array’s index.

Linked ListLinked List
•A sequence of zero or more nodes A sequence of zero or more nodes
each containing two kinds of each containing two kinds of
information: some data and one or information: some data and one or
more links called pointers to other more links called pointers to other
nodes of the linked list.nodes of the linked list.
•Singly linked list (next pointer)Singly linked list (next pointer)
•Doubly linked list (next + previous Doubly linked list (next + previous
pointers)pointers)

Arrays

fixed length (need preliminary
reservation of memory)

contiguous memory locations

direct access

Insert/delete

Linked Lists

dynamic length

arbitrary memory locations

access by following links

Insert/delete
…a1 ana2 .

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-31
Stacks and QueuesStacks and Queues

StacksStacks
•A stack of plates A stack of plates
–insertion/deletion can be done only at the top.insertion/deletion can be done only at the top.
–LIFOLIFO
•Two operations (push and pop)Two operations (push and pop)

QueuesQueues
•A queue of customers waiting for services A queue of customers waiting for services
–Insertion/enqueue from the rear and deletion/dequeue from Insertion/enqueue from the rear and deletion/dequeue from
the front.the front.
–FIFOFIFO
•Two operations (enqueue and dequeue)Two operations (enqueue and dequeue)

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-32
Priority Queue and HeapPriority Queue and Heap

Priority queues (implemented using heaps)

A data structure for maintaining a set of
elements, each associated with a key/priority,
with the following operations

Finding the element with the highest priority

Deleting the element with the highest priority

Inserting a new element

Scheduling jobs on a shared computer
9
6 8
523
965823

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-33
GraphsGraphs

Formal definitionFormal definition
•A graph A graph G = <V, E>G = <V, E> is defined by a pair of two sets: a is defined by a pair of two sets: a
finite set V of items called finite set V of items called verticesvertices and a set E of vertex and a set E of vertex
pairs called pairs called edgesedges..

Undirected Undirected and and directeddirected graphs ( graphs (digraphsdigraphs).).
What’s the maximum number of edges in an undirected What’s the maximum number of edges in an undirected
graph with |V| vertices?graph with |V| vertices?

Complete, dense,Complete, dense, andand sparsesparse graphs graphs
•A graph with every pair of its vertices connected by an A graph with every pair of its vertices connected by an
edge is called complete, Kedge is called complete, K
|V||V|
12
34

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-34
Graph RepresentationGraph Representation

Adjacency matrixAdjacency matrix
•n x n boolean matrix if |V| is n.n x n boolean matrix if |V| is n.
•The element on the ith row and jth column is 1 if there’s an The element on the ith row and jth column is 1 if there’s an
edge from ith vertex to the jth vertex; otherwise 0.edge from ith vertex to the jth vertex; otherwise 0.
•The adjacency matrix of an undirected graph is symmetric.The adjacency matrix of an undirected graph is symmetric.

Adjacency linked listsAdjacency linked lists
•A collection of linked lists, one for each vertex, that contain all A collection of linked lists, one for each vertex, that contain all
the vertices adjacent to the list’s vertex.the vertices adjacent to the list’s vertex.

Which data structure would you use if the graph is a 100-node Which data structure would you use if the graph is a 100-node
star shape?star shape?

0 1 1 1
0 0 0 1
0 0 0 1
0 0 0 0
234
4
4

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-35
Weighted GraphsWeighted Graphs

Weighted graphsWeighted graphs
•Graphs or digraphs with numbers assigned to the edges.Graphs or digraphs with numbers assigned to the edges.
12
34
6
8
5
7
9

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-36
Graph Properties -- Paths and ConnectivityGraph Properties -- Paths and Connectivity
PathsPaths
•A path from vertex u to v of a graph G is defined as a sequence of A path from vertex u to v of a graph G is defined as a sequence of
adjacent (connected by an edge) vertices that starts with u and ends adjacent (connected by an edge) vertices that starts with u and ends
with v.with v.
•Simple pathsSimple paths: All edges of a path are distinct.: All edges of a path are distinct.
•Path lengths: the number of edges, or the number of vertices – 1.Path lengths: the number of edges, or the number of vertices – 1.
Connected graphsConnected graphs
•A graph is said to be connected if for every pair of its vertices u and A graph is said to be connected if for every pair of its vertices u and
v there is a path from u to v.v there is a path from u to v.
Connected componentConnected component
•The maximum connected subgraph of a given graph.The maximum connected subgraph of a given graph.

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-37
Graph Properties -- AcyclicityGraph Properties -- Acyclicity

CycleCycle
•A simple path of a positive length that starts and A simple path of a positive length that starts and
ends a the same vertex.ends a the same vertex.

Acyclic graphAcyclic graph
•A graph without cyclesA graph without cycles
•DAG DAG (Directed Acyclic Graph)(Directed Acyclic Graph)
12
34

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-38
TreesTrees
TreesTrees
•A tree (or A tree (or free treefree tree) is a connected acyclic graph.) is a connected acyclic graph.
•Forest: a graph that has no cycles but is not necessarily connected.Forest: a graph that has no cycles but is not necessarily connected.
Properties of treesProperties of trees
•For every two vertices in a tree there always exists exactly one For every two vertices in a tree there always exists exactly one
simple path from one of these vertices to the other. simple path from one of these vertices to the other. Why?Why?
–Rooted treesRooted trees:: The above property makes it possible to select an The above property makes it possible to select an
arbitrary vertex in a free tree and consider it as the root of the arbitrary vertex in a free tree and consider it as the root of the
so called rooted tree.so called rooted tree.
–Levels in a rooted tree.Levels in a rooted tree.

|E| = |V| - 113
24
5
1
3
2
4 5
rooted

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-39
Rooted Trees (I)Rooted Trees (I)

AncestorsAncestors
•For any vertex For any vertex vv in a tree in a tree TT, all the vertices on the simple path , all the vertices on the simple path
from the root to that vertex are called ancestors.from the root to that vertex are called ancestors.

DescendantsDescendants
•All the vertices for which a vertex All the vertices for which a vertex vv is an ancestor are said to is an ancestor are said to
be descendants of be descendants of vv..

Parent, childParent, child and and siblingssiblings
•If If (u, v)(u, v) is the last edge of the simple path from the root to is the last edge of the simple path from the root to
vertex vertex vv, , uu is said to be the parent of is said to be the parent of vv and and vv is called a child is called a child
of of uu..
•Vertices that have the same parent are called siblings.Vertices that have the same parent are called siblings.

LeavesLeaves
•A vertex without children is called a leaf.A vertex without children is called a leaf.

SubtreeSubtree
•A vertex A vertex vv with all its descendants is called the subtree of with all its descendants is called the subtree of TT
rooted at rooted at vv..

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-40
Rooted Trees (II)Rooted Trees (II)

DepthDepth of a vertex of a vertex
•The length of the simple path from the root to the vertex.The length of the simple path from the root to the vertex.

HeightHeight of a tree of a tree
•The length of the longest simple path from the root to a leaf.The length of the longest simple path from the root to a leaf.
1
3
2
4 5
h = 2

Karpagam Academy of Higher Education Design & Analysis of Algorithms, 1-41
Ordered TreesOrdered Trees

Ordered treesOrdered trees
•An ordered tree is a rooted tree in which all the children of each An ordered tree is a rooted tree in which all the children of each
vertex are ordered.vertex are ordered.

Binary treesBinary trees
•A binary tree is an ordered tree in which every vertex has no more A binary tree is an ordered tree in which every vertex has no more
than two children and each children is designated s either a left child than two children and each children is designated s either a left child
or a right child of its parent.or a right child of its parent.

Binary search treesBinary search trees
•Each vertex is assigned a number.Each vertex is assigned a number.
•A number assigned to each parental vertex is larger than all the A number assigned to each parental vertex is larger than all the
numbers in its left subtree and smaller than all the numbers in its numbers in its left subtree and smaller than all the numbers in its
right subtree.right subtree.

loglog
22nn  h h  n – 1 n – 1, where h is the height of a binary tree and n the size., where h is the height of a binary tree and n the size.
9
6 8
523
6
3 9
258
Tags