Meeting 3
Meeting 3
Meeting 3
MEETING 3
Introduction
• A tree is a data structure that stores elements hierarchically.
• Each element in a tree has a parent element and zero or more children
elements, Except the Top Element.
• A→B→D→E→C→F→G
Tree Traversal – Preorder Traversal
Preorder Traversal of a Binary Tree
Tree Traversal – Postorder Traversal
• In this traversal method, the root node is visited
last, hence the name. First we traverse the left sub-
tree, then the right sub-tree and finally the root
node.
• We start from A, and following pre-order traversal,
we first visit the left sub-tree B. B is also traversed
post-order. The process goes on until all the nodes
are visited. The output of post-order traversal of
this tree will be −
• D→ E→ B → F →G →C→A
Tree Traversal – Postorder Traversal
Postorder Traversal of a Binary Tree
Inorder Traversal of a Binary Tree
• In this traversal method, the left sub-tree is visited
first, then the root and later the right sub-tree. We
should always remember that every node may
represent a sub-tree itself. If a binary tree is
traversed in-order, the output will produce sorted
key values in an ascending order.
• We start from A, and following in-order traversal, we
move to its left sub-tree B. B is also traversed in-
order. The process goes on until all the nodes are
visited. The output of inorder traversal of this tree
will be:
• D→B→E→A→F→C→G
Inorder Traversal of a Binary Tree
Example
The Binary Search Tree (BST) Algorithm
Recursion
What Is Recursion?
• Recursion is a method of solving problems that involves breaking a
problem down into smaller and smaller subproblems until you get
to a small enough problem that it can be solved trivially.
• Usually recursion involves a function calling itself. While it may not
seem like much on the surface, recursion allows us to write elegant
solutions to problems that may otherwise be very difficult to
program.
Analysis of recursive algorithm: back substitution method
Example
• T(n) = c + T (n-1) (1)
• Which means that the time complexity of the time series T(n) is equal to constant
(denoted by c) that represents a constant amount of operations that should occur (for
example checking if n is greater than 1 ) in addition to the call of T(n-1)
• Using back substitution method:
A(n)
• T(n-1) = c + T(n-2) (2)
{
• T(n-2) = c + T(n-3) (3)
if (n > 1)
• From equations 1, 2, and 3
return A(n-1)
• At step K T(n) = kc + T(n-k)
else
• This T(n) will stop once n-k = 1 which implies that k = n-1
return 1
• And hence T(n) = (n-1) c + T(n-(n-1)) = n c – c +1 O(n)
Analysis of recursive algorithm: back substitution method
Example
= n + T (n-1) at n>1 (1)
T(n)
=1 elsewhere
Solution: