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

CSG2A3

ALGORITMA dan STRUKTUR DATA

Tree Data Structure


Definition
The data structure consists of a root, and
sub trees in a hierarchical arrangement.
A form of non-linear data structures

2
Definition
Usually used to describe, hierarchical data
relationships, such as :
– organizational structure
– classification tree / genealogy
– syntax tree / tree expression

3
Example
Organization Structure
– Family tree
– Tournament tree

4
Example
Organization Structure
Arithmetic expression
Example : (4+3*7)-(5/(3+4)+6

5
Example
Organization Structure
Arithmetic expression
Decision Tree

6
Tree Terminology
Leaf
Connection between nodes
– (parent, child, sibling)
Level
Degree
Height and depth
Ancestor and Descendant
Forest

7
Tree Terminology
Tree is a collection of many nodes
Each node may have 0 or more successor
Each node has precisely one predecessor
– except the peak node (root)

Root is the top node in a tree


Links that connect a node to its successors are
called branches / edges

8
Tree Terminology
Successors of a node are called children (child)
Predecessor of a node is called parent
Nodes with the same parent are called siblings
Nodes with no children are called leaf/external
node
Number of children / sub trees of a node is
called degree

9
Tree Terminology
Descendant is a list of all child / successor to the
leaf
Ancestor is a list of predecessor / from parent to
root
The level of a node is defined by 1 + the number
of connections between the node and the root.

10
Tree Terminology
The height of a tree is the number of edges on
the longest downward path between the root and
a leaf.
The height of a node is the number of edges on
the longest downward path between that node
and a leaf.
The depth of a node is the number of edges from
the node to the tree's root node

11
Terminology
Degree = 2
Root
Degree = 3

Node / Vertex

Degree = 0

12
Exercise on Tree Terminology
Root =
Sibling C =
Parent F =
Child B =
Leaf =
Internal Node =
Level E =
Tree height =
Degree B =
Ancestor I =
Descendant B =

13
Exercise on Tree Terminology
Create the tree
Dataset: {A, X, W, H, B, E, S}
Root: A
Ancestor of S: {E, A}
{X, W, E} are siblings
{H, B} are descendant and both are children of W

14
Question?
Tree Notations / Representing Tree
Tree Diagram Notation
– Classical node-link diagrams

Venn Diagram Notation


– Nested sets / Tree Maps

Bracket Notation
– Nested Parentheses

Level Notation
– Outlines / tree views

16
Tree Diagram Notation

17
Venn Diagram Notation

18
Bracket Notation

19
Level Notation

20
Exercise on Tree Notation
Create the tree in Venn Diagram, Bracket, and
level notation
X

Y R S

Q T U W Z

P M N

21
Question?
THANK YOU
23
CSG2A3
ALGORITMA dan STRUKTUR DATA

Tree Data Structure


Binary Tree Data Structure

2
Binary Tree
Tree Data Structure with maximum child (degree)
of 2, which are referred to as the left child and
the right child.

3
Properties of Binary Tree
The number of nodes n a full binary tree is
– At least :
– At most :
– Where h is the height of the tree

Maximum Node for each level = 2n

4
Types of Binary Tree
Full Binary Tree
Complete Binary Tree
Skewed Binary Tree

5
Full Binary Tree
A tree in which every node other than the leaves
has two children
– sometimes called proper binary tree or 2-tree

6
Complete Binary Tree
a binary tree in which every level, except possibly
the last, is completely filled, and all nodes are as
far left as possible

A A A A A

B B C B C B C

D D E

7
Skewed Tree
Binary Tree with an unbalanced branch between
left and right branch

8
ADT Binary Tree
Array Representation
Linked list representation

id value

1 A
2 B
3 C
4 D
5 E
6 F
7 G

9
Array Representation
if a node has an index i, its children are found at
indices :
– Left child : 2i + 1
– Right child : 2i + 2
𝑖−1
while its parent (if any) is found at index
2
– (assuming the root has index zero)

10
Array Representation
Problem :
1 2 3 4 5 6 7 8 … 16

A B - C - - - D … E

– Waste space
– Insertion / deletion problem

Array Representation is good for


Complete Binary Tree types
– Binary Heap Tree

11
Linked List Representation
Type infotype : integer
Type address : pointer to Node left Info right

Type Node <


info : infotype
left : address
right : address
> Type BinTree : address

Dictionary
root : BinTree

12
Traversal on Binary Tree
DFS traversal
– Pre-order
– In-order
– Post-order

BFS traversal
– Level-order

13
Pre-order Traversal
Deep First Search
Root → Left → Right
– Prefix notation

Result :
– FBADCEGIH

14
Pre-order Traversal
Procedure preOrder( i/o root : tree )
Algorithm
if ( root != null ) then
output( info( root ) )
preOrder( left( root ) )
preOrder( right( root ) )

15
In-order Traversal
Left → Root → Right
– Infix notation

Result :
– ABCDEFGHI

16
In-order Traversal
Procedure inOrder( i/o root : tree )
Algorithm
if ( root != null ) then
inOrder( left( root ) )
output( info( root ) )
inOrder( right( root ) )

17
Post-order Traversal
Left → right → Root
– Postfix notation

Result :
– ACEDBHIGF

18
Post-order Traversal
Procedure postOrder( i/o root : tree )
Algorithm
if ( root != null ) then
postOrder( left( root ) )
postOrder( right( root ) )
output( info( root ) )

19
Level-order Traversal
Breadth First Search
recursively at each node
Result :
– FBGADICEH

20
Level-order Traversal
Procedure levelOrder( root : tree )
Dictionary
Q : Queue
Algorithm
enqueue( Q, root )
while ( not isEmpty(Q) )
n  dequeue( Q )
output( n )
enqueue( child ( n ) )

21
Exercise – write the traversal - 1

22
Exercise – write the traversal - 2

23
Exercise – write the traversal - 3

24
Exercise – write the traversal - 4

25
Exercise – Create the Tree
Assume there is ONE tree, which if traversed by
Inorder resulting : EACKFHDBG, and when
traversed by Preorder resulting : FAEKCDHGB
Draw the tree that satisfy the condition above

26
Question?
THANK YOU
28
CSG2A3
ALGORITMA dan STRUKTUR DATA

Recursive Algorithm
What is recursion?
Sometimes, the best way to solve a problem is by
solving a smaller version of the exact same
problem first
Example problem:
– Try to tear a sheet of paper into the same 8 pieces

2
Tear paper into the same 8 pieces
To solve this, one solution is that we can just tear
it 7 times as follows:
1 2 3 4 5 6 7 8

That was an example of the application of looping

3
Tear paper into the same 8 pieces
Or we can tear it into 2, and repeat the process
for each pieces 2 times

a b

That is an example of the application of recursive


4
Recursive Function
Function that calls itself within the program text

5
Have you seen this movie?
The movie tells about someone
who can dream inside a dream

If you think that the “dream” in


the movie is a function, then you’ll
find it really similar concept to the
recursive function

6
Some Definitions
Recursion is a technique that solves a problem by
solving a smaller problem of the same type
Recursion is a principle closely related to
mathematical induction.

F(0) = 0 0
F(x) =
F(x) = F(x-1) + 2 F(x-1) + 2

7
Example
Power of two
2n = 2 * 2n-1
20 = 1

Factorial
X! = X * (X-1)!
0! = 1

8
Careful when writing
If we use iteration, we must be careful
not to create an infinite loop by accident:
While ( result > 0 ) do
result ++
Oops!
Careful when writing
Similarly, if we use recursion we must be
careful not to create an infinite chain of
function calls
Remember the Rule!
An Algorithm must stop!
Define a rule that will stop the recursion
(initial set / base case)
– X! = X * (X-1)!
– 0! = 1

Define a rule to reach the next iteration


(construct new element / step)

11
Algorithm of the factorial function
Function Factorial(input : n : integer)
if (n == 0) then // base case
→1
else
→ n * Factorial(n-1)
A famous example: The Fibonacci
numbers
f(0) = 0, f(1) = 1
f(n) = f(n – 1) + f(n - 2) f(0) = 0
f(1) = 1
f(2) = f(1) + f(0) = 1 + 0 = 1
f(3) = f(2) + f(1) = 1 + 1 = 2
f(4) = f(3) + f(2) = 2 + 1 = 3
f(5) = f(4) + f(3) = 3 + 2 = 5
f(6) = f(5) + f(4) = 5 + 3 = 8

14
Recursive Algorithm
An algorithm is called recursive if it solves a
problem by reducing it to an instance of the same
problem with smaller input
A recursive function must contain at least one
non-recursive branch.
The recursive calls must eventually lead to a non-
recursive branch

15
Recursion vs. iteration
For every recursive algorithm, there is an
equivalent iterative algorithm
Iteration can be used in place of recursion
– An iterative algorithm uses a looping construct
– A recursive algorithm uses a branching structure

16
Recursion vs. iteration
Recursive solutions are often less efficient, in
terms of both time and space, than iterative
solutions
Recursion can simplify the solution of a problem,
often resulting in shorter, more easily understood
source code

17
How do I write a recursive function?
Determine the size factor
Determine the base case(s)
(the one for which you know the answer)

Determine the general case(s)


(the one where the problem is expressed as a smaller
version of itself)

Verify the algorithm


(use the "Three-Question-Method")
Three-Question Verification Method
The Base-Case Question:
– Is there a non-recursive way out of the function, and does
the routine work correctly for this "base" case?

The Smaller-Caller Question:


– Does each recursive call to the function involve a smaller
case of the original problem, leading inescapably to the
base case?

The General-Case Question:


– Assuming that the recursive call(s) work correctly, does
the whole function work correctly?

19
Question?
Write a recursive Algorithm
Binary Search
Reverse an Array
Counts number of zero
Checking a Palindrome
Drawing a triangle
Example :
*
**
***
****

21
THANK YOU
22

You might also like