• Tidak ada hasil yang ditemukan

Recursive View: a binary tree is either

N/A
N/A
Protected

Academic year: 2019

Membagikan "Recursive View: a binary tree is either"

Copied!
10
0
0

Teks penuh

(1)

Outline

• Tree Data Structure

– Examples

– Terminology & Definition

• Binary Tree

• Tree Traversal

• Tree Iterators

Trees: Some Examples

• A tree

represents a hierarchy, for example:

– Organizational structure of a company

Trees: Some Examples

(2)

Trees: Some Examples

– File system (Unix, Windows, Internet)

Trees: Terminology

Ais the root node

Bis the parentof Dand E

Cis the siblingof B

Dand E are the children of B

D, E, F, G, Iare external nodes, or

leaves

A, B, C, Hare internal nodes

The depth, level, orpath lengthof E is 2

The heightof the tree is 3 The degreeof node Bis 2

Trees: Viewed Recursively

A sub-tree is also a tree!!

Binary Trees

Binary tree: tree with all internal nodes of degree 2

Recursive View: a binary tree is either

empty

an internal node (the root) and two binary trees(left subtree

(3)

Binary Trees: An Example

• Arithmetic expression

• If we restrict that each parent can have two and only two children, then:

Binary Trees: Properties

– |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

Traversing Trees: Preorder

• Preorder Traversal

Algorithm preOrder(v)

“visit” node v

for each child wof vdo

recursively perform preOrder(w)

• Example: reading a document from beginning

to end

Traversing Trees: Postorder

Postorder Traversal

AlgorithmpostOrder(v) for eachchild wof vdo

recursively perform postOrder(w) “visit” node v

(4)

Traversing Trees

• Algorithm

evaluateExpression

(

v

)

if vis 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

Traversing Trees: Inorder

• Inorder traversal of a binarytree Algorithm inOrder(v)

recursively perform inOrder(leftChild(v))

“visit” node v

recursively perform inOrder(rightChild(v))

• Example: printing an arithmetic expression – print “(“ before traversing the left subtree – print “)” after traversing the right subtree

The

BinaryNode

in Java

A tree is a collection of nodes: class BinaryNode <T>

{

T element; /* Item stored in node */ BinaryNode<T> left;

BinaryNode<T> right; }

The tree stores a reference to the root node, which is the starting point.

public class BinaryTree <T> {

private BinaryNode<T> root; // Root node public BinaryTree() // Default constructor {

root = null; }

}

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

(5)

Routine to Compute Height

• Handle base case (empty tree)

• Use previous observation for recursive case.

public static int height (BinaryNode t) {

if (t == null) return 0; else

return 1 + max(height (t.left), height (t.right)); }

Running Time

• This strategy is a

postorder

traversal:

information for a tree node is computed

after

the information for its children is computed.

• The running time of tree traversal is

N

times

the cost of processing each node.

• Thus, the running time is linear because we do

constant work for each node in the tree.

Print Preorder

class BinaryNode {

void printPreOrder( ) {

System.out.println( element ); // Node if( left != null )

public void printPreOrder( ) {

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( ); }

(6)

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( ); }

}

Traversing Tree

Exercise

• A tree contains Integer objects.

– Find the maximum value – Find the total value

Tree Iterator Class

Can we implement traversal

non-recursively

?

Recursion is implemented by using a stack. We can traverse non-recursively by maintaining the stack ourselves (emulate stack of activation records).

Is a non-recursive approach faster than

recursive approach?

(7)

Postorder 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

We “pop” each node three times, when:

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 itself

Postorder Algorithm

init: push root onto 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 of X (if it exists) with state 0 case 1:

push node X with state 2

push right child of X (if it exists) with state 0 case 2:

visit/processnode X

Postorder Traversal: Stack States

Exercise

• Create a non-recursive algorithm for inorder

traversal using stack.

• Create a non-recursive algorithm for preorder

(8)

Inorder Traversal using Stack

• What are the states for

inorder

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

Inorder Algorithm

init: push root onto 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 of X (if it exists) with state 0 case 1:

push node X with state 2

visit/processnode X case 2:

push right child of X (if it exists) with state 0

Inorder Algorithm (improved)

• init:

push root

onto 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 of X (if it exists) with state 0 – case 1:

»visit/processnode X

» push right child of X (if it exists) with state 0

Preorder Traversal using Stack

• What are the states for

preorder

traversal?

0. about to process the current node

(9)

Preorder Algorithm

init: push rootonto 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

visit/processthe node X case 1:

push node X with state 2

push left child of X (if it exists) with state 0 case 2:

push right child of X (if it exists) with state 0

Preorder Algorithm (improved)

• init:

push root

onto the stack

• advance (optimized):

– while (true)

• node X = pop from the stack

•visit/processnode X

• push right child of X (if it exists) • push left child of X (if it exists)

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

Level-Order Traversal: Idea

• Using a

queue

instead of a stack

• Algorithm (similar to pre-order)

– init: enqueue the rootinto the queue – while(true):

• node X = dequeue from the queue

• visit/processnode X;

(10)

Binary Tree: Properties

Maximum number of nodes in a binary tree of height k is 2k+1-1.

A full binary treewith height k is a binary tree which has 2k+1- 1 nodes.

A complete binary treewith 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.

Complete binary treewith nnodes 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)

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-order the right subtrees followed by visit to the node.

Breadth First Search (BFS):

Referensi

Dokumen terkait

Pada hari ini Senin tanggal Sembilan belas bulan September tahun Dua Ribu Enam Belas, Pokja ULP Kegiatan Pengadaan/ Pembebasan Lahan/Tanah/Bangunan untuk Pekerjaan

Simpulan dari hasil penelitian ini adalah: pertama, model pengukuran konstrak kesehatan spiritual yang dikembangkan oleh Fisher adalah valid dan dapat diandalkan; kedua,

This was a survey study that used the descriptive data, Customer Response Index (CRI) and independent samples t-test to test the difference in effectiveness between the

Dan eksistensi hakam dalam rangka pencegahan perceraian di Kelurahan Limpomajang Kecamatan Marioriawa Kabupaten Soppeng adalah sebagai arbitrase atau penengah yang

Rantai yang sebelah tepi dari residu-residu histidin (asam amino E7 dan F8 di dalam rantai α dan β) terletak pada tiap tepi bidang datar dari kelompok heme yang berinteraksi

3.1.1 Memahami cara menggambar bukaan benda dengan baik dan benar 3.1.2 Memahami cara membuat gambar bukaan benda terpancung dengan.. baik

Berdasarkan masalah diatas maka tujuan yang ingin dicapai dari penelitian ini adalah untuk mengetahui: (1) model pembelajaran manakah yang memberikan prestasi

sangat valid (4,2), respon guru terhadap LKS memperoleh kategori sangat membantu (4,2) dan lebih dari 80% siswa memberikan respon positif terhadap LKS sehingga