Struktur Data & Algoritme ( Data Structures & Algorithms ) - - PDF document

struktur data algoritme data structures algorithms
SMART_READER_LITE
LIVE PREVIEW

Struktur Data & Algoritme ( Data Structures & Algorithms ) - - PDF document

Struktur Data & Algoritme ( Data Structures & Algorithms ) Tree Denny ( denny@cs.ui.ac.id ) Suryana Setiawan ( setiawan@cs.ui.ac.id ) Fakultas I lm u Kom puter Universitas I ndonesia Sem ester Genap - 2 0 0 4 / 2 0 0 5 Version 2 .0 -


slide-1
SLIDE 1

1

Struktur Data & Algoritme ( Data Structures & Algorithms)

Denny (denny@cs.ui.ac.id) Suryana Setiawan (setiawan@cs.ui.ac.id)

Fakultas I lm u Kom puter Universitas I ndonesia Sem ester Genap - 2 0 0 4 / 2 0 0 5

Version 2 .0 - I nternal Use Only

Tree

SDA/ TREE/ V2.0/ 2

Objectives

understands the definition and terminology of a

general tree

know applications of the tree know how to traverse of a tree

slide-2
SLIDE 2

2

SDA/ TREE/ V2.0/ 3

Outline

Tree example terminology/definition binary tree traversal of trees iterator

SDA/ TREE/ V2.0/ 4

Examples

a tree represents a hierarchy

  • rganization structure of a corporation
slide-3
SLIDE 3

3

SDA/ TREE/ V2.0/ 5

Examples

table of contents of a book

SDA/ TREE/ V2.0/ 6

Examples

Unix or DOS/Windows file system

slide-4
SLIDE 4

4

SDA/ TREE/ V2.0/ 7

Terminology

A is the root node B is the parent of D and E C is the sibling of B D and E are the children of B D, E, F, G, I are external

nodes, or leaves

A, B, C, H are internal nodes The depth/level/path length

  • f E is 2

The height of the tree is 3 The degree of node B is 2 Property: (# edges) =

(#nodes) - 1

SDA/ TREE/ V2.0/ 8

Tree Viewed Recursively

The sub-tree is also a tree!!

slide-5
SLIDE 5

5

SDA/ TREE/ V2.0/ 9

Binary Tree

Binary tree: tree with all internal nodes of degree 2 Recursive View: Binary tree is either empty an internal node (the root) and two binary trees (left

subtree and right subtree)

Ordered/Search tree: the children of each node are

  • rdered

SDA/ TREE/ V2.0/ 10

Examples of Binary Tree

arithmetic expression

slide-6
SLIDE 6

6

SDA/ TREE/ V2.0/ 11

Properties of Binary Trees

If we restrict that each parent can have two and only two

children, then:

(# external nodes ) = (# internal nodes) + 1 (# nodes at level i) ≤ 2i (# external nodes) ≤ 2 (height) (height) ≥ log2 (# external nodes) (height) ≥ log2 (# nodes) - 1 (height) ≤ (# internal nodes) = ((# nodes) - 1)/2

SDA/ TREE/ V2.0/ 12

Traversing Trees

preorder traversal

Algorithm preOrder(v) “visit” node v for each child w of v do recursively perform preOrder(w)

reading a document from beginning to end

slide-7
SLIDE 7

7

SDA/ TREE/ V2.0/ 13

Traversing Trees

postorder traversal

Algorithm postOrder(v) for each child w of v do recursively perform postOrder(w) “visit” node v

du (disk usage) command in

Unix

SDA/ TREE/ V2.0/ 14

Traversing Trees

Algorithm evaluateExpression(v)

if v is an external node return the variable stored at v else let o be the operator stored at v x ← evaluateExpression(leftChild(v)) y ← evaluateExpression(rightChild(v)) return x o y

slide-8
SLIDE 8

8

SDA/ TREE/ V2.0/ 15

Traversing Trees

inorder traversal of a

binary tree Algorithm inOrder(v) recursively perform inOrder(leftChild(v)) “visit” node v recursively perform inOrder(rightChild(v))

printing an arithmetic

expression

print “(“ before

traversing the left subtree

print “)” after

traversing the right subtree

SDA/ TREE/ V2.0/ 16

The BinaryNode in Java

The tree is a collection of nodes: class BinaryNode { Object element; /* Item stored in node */ BinaryNode left; BinaryNode right; } The tree stores a reference to the root node, which is

the starting point.

public class BinaryTree { private BinaryNode root; public BinaryTree( ) { root = null; } }

slide-9
SLIDE 9

9

SDA/ TREE/ V2.0/ 17

Think Recursively

Computing the height of a tree is complex without

recursion.

The height of a tree is one more than the maximum of

the heights of the subtrees.

HT = max (HL+1, HR+1)

HL HR HL+1 HR+1

SDA/ TREE/ V2.0/ 18

Routine to Compute Height

Handle base case (empty tree) Use previous observation for other case.

public static int height (TreeNode t) { if (t == null) { return 0; } else { return 1 + max(height (t.left), height (t.right)); } }

slide-10
SLIDE 10

10

SDA/ TREE/ V2.0/ 19

Running Time

This strategy is a postorder traversal: information for

a tree node is computed after the information for its children is computed.

Postorder traversal running time is N times the cost

  • f processing each node.

The running time is linear because we do constant

work for each node in the tree.

SDA/ TREE/ V2.0/ 20

Print Pre-Order

class BinaryNode { void printPreOrder( ) { System.out.println( element ); // Node if( left != null ) left.printPreOrder( ); // Left if( right != null ) right.printPreOrder( ); // Right } } class BinaryTree { public void printPreOrder( ) { if( root != null ) root.printPreOrder( ); } }

slide-11
SLIDE 11

11

SDA/ TREE/ V2.0/ 21

Print Post-Order

class BinaryNode { void printPostOrder( ) { if( left != null ) left.printPostOrder( ); // Left if( right != null ) right.printPostOrder( ); // Right System.out.println( element ); // Node } } class BinaryTree { public void printPostOrder( ) { if( root != null ) root.printPostOrder( ); } }

SDA/ TREE/ V2.0/ 22

Print InOrder

class BinaryNode { void printInOrder( ) { if( left != null ) left.printInOrder( ); // Left System.out.println( element ); // Node if( right != null ) right.printInOrder( ); // Right } } class BinaryTree { public void printInOrder( ) { if( root != null ) root.printInOrder( ); } }

slide-12
SLIDE 12

12

SDA/ TREE/ V2.0/ 23

Traversing Tree

Pre-Order Post-Order InOrder

SDA/ TREE/ V2.0/ 24

Exercise

A tree contains Integer objects. Find the maximum value Find the total value

slide-13
SLIDE 13

13

SDA/ TREE/ V2.0/ 25

Iterator Class

Problems with recursive: Can not process step-by-step (ie. using loop) How to avoid recursive? How to implement non-

recusive traversal?

Recursion is implemented by using a stack. We can traverse nonrecursively by maintaining the

stack ourselves (emulate stack of activation records).

Is non-recursive approach faster than recursive

approach?

Yes Why? We can place only the essentials, while the compiler

place an entire activation record.

SDA/ TREE/ V2.0/ 26

Tree Iterator: implementation

see online code

http://telaga.cs.ui.ac.id/WebKuliah/IKI101 00/resources/code/DataStructures/TreeItera tor.java

slide-14
SLIDE 14

14

SDA/ TREE/ V2.0/ 27

Post-Order Traversal using Stack

Use stack to store the current state (nodes we have

traversed but not yet completed)

similar to PC (program counter) in the activation record What are the states for post-order traversal?

  • 0. about to make a recursive call to left subtree
  • 1. about to make a recursive call to right subtree
  • 2. about to process the current node

SDA/ TREE/ V2.0/ 28

Post-Order Algorithm/ Pseudocode

init: push the root into the stack with state 0 advance: while (true)

  • node X = pop from the stack
  • switch (state X):
  • case 0:
  • push node X with state 1;
  • push left child node X (if it exists) w/ state 0;
  • break;
  • case 1:
  • push node X with state 2;
  • push right child node X (if it exists) w/ state 0;
  • break;
  • case 2:
  • “visit”/ ”set current to” the node X; return;
slide-15
SLIDE 15

15

SDA/ TREE/ V2.0/ 29

Post-Order traversal: stack states

SDA/ TREE/ V2.0/ 30

Post-Order: Implementation

see online code

http://telaga.cs.ui.ac.id/WebKuliah/IKI10100/res

  • urces/code/DataStructures/PostOrder.java

http://telaga.cs.ui.ac.id/WebKuliah/IKI10100/res

  • urces/code/DataStructures/StNode.java
slide-16
SLIDE 16

16

SDA/ TREE/ V2.0/ 31

Exercise

Create an algorithm/psedo-code for in-order traversal

using stack.

Create an algorithm/psedo-code for pre-order

traversal using stack.

SDA/ TREE/ V2.0/ 32

In-Order Traversal using Stack

What are the states for in-order traversal?

  • 0. about to make a recursive call to left subtree
  • 1. about to process the current node
  • 2. about to make a recursive call to right subtree
slide-17
SLIDE 17

17

SDA/ TREE/ V2.0/ 33

In-Order Algorithm/ Pseudocode

init: push the root into the stack with state 0 advance: while (true)

  • node X = pop from the stack
  • switch (state X):
  • case 0:
  • push node X with state 1;
  • push left child node X (if it exists) w/ state 0;
  • break;
  • case 1:
  • push node X with state 2;
  • “visit”/ ”set current to” the node X; return;
  • case 2:
  • push right child node X (if it exists) w/ state 0;
  • break;

SDA/ TREE/ V2.0/ 34

In-Order Algorithm/ Pseudocode

init: push the root into the stack with state 0 advance (optimize): while (true)

  • node X = pop from the stack
  • switch (state X):
  • case 0:
  • push node X with state 1;
  • push left child node X (if it exists) w/ state 0;
  • break;
  • case 1:
  • “visit”/ ”set current to” the node X;
  • push right child node X (if it exists) w/ state 0;
  • return;
slide-18
SLIDE 18

18

SDA/ TREE/ V2.0/ 35

In-Order: Implementation

see online code

http://telaga.cs.ui.ac.id/WebKuliah/IKI101 00/resources/code/DataStructures/InOrder.j ava

SDA/ TREE/ V2.0/ 36

Pre-Order Traversal using Stack

What are the states for in-order traversal?

  • 0. about to process the current node
  • 1. about to make a recursive call to left subtree
  • 2. about to make a recursive call to right subtree
slide-19
SLIDE 19

19

SDA/ TREE/ V2.0/ 37

Pre-Order Algorithm/ Pseudocode

init: push the root into the stack with state 0 advance: node X = pop from the stack while (true)

  • switch (state X):
  • case 0:
  • push node X with state 1;
  • “visit”/ ”set current to” the node X; return;
  • case 1:
  • push right child node X (if it exists) w/ state 0;
  • push node X with state 2;
  • break;
  • case 2:
  • push left child node X (if it exists) w/ state 0;
  • break;

SDA/ TREE/ V2.0/ 38

Pre-Order Algorithm/ Pseudocode

init: push the root into the stack advance (optimized): node X = pop from the stack “visit”/”set current to” the node X; push right child node X (if it exists); push left child node X (if it exists); return

slide-20
SLIDE 20

20

SDA/ TREE/ V2.0/ 39

Pre-Order: Implementation

see online code

http://telaga.cs.ui.ac.id/WebKuliah/IKI101 00/resources/code/DataStructures/PreOrder. java

SDA/ TREE/ V2.0/ 40

Euler Tour Traversal

generic traversal of a binary tree the preorder, inorder, and postorder traversals are special cases

  • f the Euler tour traversal

“walk around” the tree and visit each node three times:

  • n the left

from below

  • n the right
slide-21
SLIDE 21

21

SDA/ TREE/ V2.0/ 41

Level-order Traversal

Visit root followed by its children from left to right

and followed by their children. So we go down the tree level by level.

Sequence: A - B - C - D - E - F - G - H - I

SDA/ TREE/ V2.0/ 42

Level-order Traversal: idea

Using a queue instead of a stack Algorithm (similar to pre-order) init: enqueue the root into the queue advance:

  • node X = dequeue from the queue
  • “visit”/ ”set current to” the node X;
  • enqueue left child node X (if it exists);
  • enqueue right child node X (if it exists);
slide-22
SLIDE 22

22

SDA/ TREE/ V2.0/ 43

Level-order: implementation

see online code

http://telaga.cs.ui.ac.id/WebKuliah/IKI101 00/resources/code/DataStructures/LevelOrde r.java

SDA/ TREE/ V2.0/ 44

Properties of binary Tree

Maximum number of nodes in a binary tree of height

k is 2k+1 -1.

A full binary tree with height k is a binary tree which

has 2k+1 - 1 nodes.

A complete binary tree with height k is a binary tree

which has maximum number of nodes possible in levels 0 through k -1, and in (k -1)’th level all nodes with children are selected from left to right.

slide-23
SLIDE 23

23

SDA/ TREE/ V2.0/ 45

Properties of binary tree (cont.)

Complete binary tree with n nodes can be shown by

using an array, then for any node with index i, we have:

Parent (i) is at ⎣i/2⎦ if i ≠1; for i =1, we have no parent. Left-child (i ) is at 2i if 2i ≤ n. (else no left-child) Right-child (i ) is at 2i+1 if 2i +1 ≤ n (else no right-child)

SDA/ TREE/ V2.0/ 46

Summary

Tree, Binary Tree In order to process the elements of a tree, we consider

accessing the elements in certain order

Tree traversal is a tree operation that involves "visiting” (or"

processing") all the nodes in a tree.

Depth First Search (DFS): Pre-order: Visit node first, pre-order all its subtrees from leftmost

to rightmost.

Inorder: Inorder the node in left subtree and then visit the root

following by inorder traversal of all its right subtrees.

Post-order: Post-order the node in left subtree and then post-

  • rder the right subtrees followed by visit to the node.

Breadth First Search (BFS): Level-order : Visit root followed by its children from left to right

and followed by their children. So we go down the tree level by level.

slide-24
SLIDE 24

24

SDA/ TREE/ V2.0/ 47

Further Reading

http://telaga.cs.ui.ac.id/WebKuliah/IKI101

00/1998/handout/handout10.html

http://telaga.cs.ui.ac.id/WebKuliah/IKI101

00/1998/handout/handout15.html

Chapter 17

SDA/ TREE/ V2.0/ 48

What’s Next

Binary Search Tree