lecture 15 trees and tree traversals -...

Post on 17-Jul-2020

12 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

CSC212 Data Structure - Section FG

Lecture15TreesandTreeTraversals

Instructor:FengHUDepartmentofComputerScience

CityCollegeofNewYork

Motivation

• Linearstructures• arrays• dynamicarrays• linkedlists

• NonlinearStructures• trees- HierarchicalStructures• Graphs

• Why???

Application:MailingAddresses

Feng HU, CS Dept, CCNY, New York, NY 10031, USA

6 billion = 6,000,000,000 people in the world

What kind of structure is the best for a postman to locate me?

Array ?

Linked list ?

Tree ?

ATreeforallthemailingaddresses

China

Earth

USA... ...Korea

NY... ...

... ...

NYC

MA ... ...

CCNY

F. HU

Albany

... ...... ...

... ...

... ...

CS

TreesandBinaryTrees

•Chapter10introducestrees.• Thispresentationillustratesbasicterminologyforbinarytrees

• andfocuseson• CompleteBinaryTrees:thesimplestkindoftrees

• BinaryTreeTraversals:anykindofbinarytrees

Data Structuresand Other ObjectsUsing C++

BinaryTrees

•Abinarytreehasnodes,similartonodesinalinkedliststructure.

•Data ofonesortoranothermaybestoredateachnode.

•Butitistheconnections betweenthenodeswhichcharacterizeabinarytree.

BinaryTrees

•Abinarytreehasnodes,similartonodesinalinkedliststructure.

•Data ofonesortoranothermaybestoredateachnode.

•Butitisthe connections betweenthenodeswhichcharacterizeabinarytree.

An example canillustrate how theconnections work

ABinaryTreeofStates

Inthisexample,thedatacontainedateachnodeisoneofthe50states.

Washington

Colorado

Oklahoma

Arkansas

Mass.

New

Ham

pshi

re

Arizona

Nebraska

ABinaryTreeofStates

Eachtreehasaspecialnodecalleditsroot,usuallydrawnatthetop.

Washington Arkansas Colorado Florida Oklahoma Arizona Mass. NewHampshire Nebraska

ABinaryTreeofStates

Eachtreehasaspecialnodecalleditsroot,usuallydrawnatthetop. The example tree

has Washingtonas its root.

Washington Arkansas Colorado Florida Oklahoma Arizona Mass. NewHampshire Nebraska

ABinaryTreeofStates

Eachnodeispermittedtohavetwolinkstoothernodes,calledtheleftchild andtherightchild.

Washington Arkansas Colorado Florida Oklahoma Arizona Mass. NewHampshire Nebraska

ABinaryTreeofStates

Eachnodeispermittedtohavetwolinkstoothernodes,calledtheleftchild andtherightchild.

Washington Arkansas Colorado Florida Oklahoma Arizona Mass. NewHampshire Nebraska

ABinaryTreeofStates

Childrenareusuallydrawnbelowanode.

The right child ofWashington is

Colorado.

The left child ofWashington is

Arkansas.

Washington Arkansas Colorado Florida Oklahoma Arizona Mass. NewHampshire Nebraska

ABinaryTreeofStates

Somenodeshaveonlyonechild.

Arkansas has aleft child, but no

right child.

Washington Arkansas Colorado Florida Oklahoma Arizona Mass. NewHampshire Nebraska

AQuiz

Somenodeshaveonlyonechild.

Which node hasonly a right child?

Washington Arkansas Colorado Florida Oklahoma Arizona Mass. NewHampshire Nebraska

AQuiz

Somenodeshaveonlyonechild.

Florida hasonly a right child.

Washington Arkansas Colorado Florida Oklahoma Arizona Mass. NewHampshire Nebraska

ABinaryTreeofStates

Anodewithnochildreniscalledaleaf.

Washington Arkansas Colorado Florida Oklahoma Arizona Mass. NewHampshire Nebraska

ABinaryTreeofStates

Eachnodeiscalledtheparent ofitschildren.

Washington is theparent of Arkansas

and Colorado.Washington Arkansas Colorado Florida Oklahoma Arizona Mass. New

Hampshire Nebraska

ABinaryTreeofStates

Tworulesaboutparents:

❶ The root has no parent.

❷ Every other node has exactly one parent.

Washington Arkansas Colorado Florida Oklahoma Arizona Mass. NewHampshire Nebraska

ABinaryTreeofStates

Twonodeswiththesameparentarecalledsiblings.

Arkansasand Coloradoare siblings.

Washington Arkansas Colorado Florida Oklahoma Arizona Mass. NewHampshire Nebraska

CompleteBinaryTrees

Acompletebinarytreeisaspecialkindofbinarytreewhichwillbeusefultous.

CompleteBinaryTrees

Acompletebinarytreeisaspecialkindofbinarytreewhichwillbeusefultous.

When a completebinary tree is built,

its first node must bethe root.

CompleteBinaryTrees

Thesecondnodeofacompletebinarytreeisalwaystheleftchildoftheroot...

CompleteBinaryTrees

Thesecondnodeofacompletebinarytreeisalwaystheleftchildoftheroot......andthethirdnodeisalwaystherightchildoftheroot.

CompleteBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright.

CompleteBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright.

CompleteBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright.

CompleteBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright.

CompleteBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright.

CompleteBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright.

IsThisComplete?

IsThisComplete?

IsThisComplete?

IsThisComplete?

IsThisComplete?

Yes!✔ Itiscalledtheemptytree,andit

hasnonodes,notevenaroot.

FullBinaryTrees

Afullbinarytreeisaspecialkindofcompletebinarytree

When a fullbinary tree is built,

its first node must bethe root.

FULL

FullBinaryTrees

Thesecondnodeofafullbinarytreeisalwaystheleftchildoftheroot...

not FULL yet

FullBinaryTrees

Thesecondnodeofafullbinarytreeisalwaystheleftchildoftheroot......andyouMUSThavethethirdnodewhichalwaystherightchildoftheroot. FULL

FullBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright.

not FULL yet

FullBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright.

not FULL yet

FullBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright.

not FULL yet

FullBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright...untileveryleafhasthesamedepth(2)

FULL!

FullBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright.

FullBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright.

IsThisFull?

IsThisFull?

IsThisFull?

IsThisFull?

IsThisFull?

Yes!✔ Itiscalledtheemptytree,andit

hasnonodes,notevenaroot.

ImplementingaCompleteBinaryTree

•Wewillstorethedatefromthenodesinapartially-filledarray.

An array of dataWe don't care what's in

this part of the array.

An integer to keeptrack of how many nodes are in the tree

3

ImplementingaCompleteBinaryTreeUsinganArray

•Wewillstorethedatefromthenodesinapartially-filledarray.

An array of dataWe don't care what's in

this part of the array.

An integer to keeptrack of how many nodes are in the tree

3

Read Section 10.2 tosee details of how

the entries are stored.

ImplementingaCompleteBinaryTreeUsinganArray

• Rootisatcomponent[0]• Parentofnodein[i]isat[(i-1)/2)• Children(ifexist)ofnode[i]isat[2i+1]and[2i+2]

• Totalnodenumber• 20+21+22+…+2d-1+r, r<=2d,disthedepth

BinaryTreeSummary

•Binarytreescontainnodes.• Eachnodemayhavealeftchildandarightchild.• Ifyoustartfromanynodeandmoveupward,youwilleventuallyreachtheroot.

• Everynodeexcepttheroothasoneparent.Theroothasnoparent.

•Completebinarytreesrequirethenodestofillineachlevelfromleft-to-rightbeforestartingthenextlevel.

BinaryTreeBasics

Abinarytreeisastructureinwhich:

Eachnodecanhaveatmosttwochildren,andinwhichauniquepathexistsfromtheroottoeveryothernode.

Thetwochildrenofanodearecalledtheleftchild andtherightchild, iftheyexist.

ABinaryTreeExercise

Q

V

T

K S

AE

L

Howmanyleafnodes?

Q

V

T

K S

AE

L

HowmanydescendantsofQ?

Q

V

T

K S

AE

L

HowmanyancestorsofK?

Q

V

T

K S

AE

L

Question: How to implement a general binary tree ?

ImplementingaBinaryTreewithaClassforNodes

Q

V

T

K S

AE

L

Root

BinaryTreeNodes

• Eachnodeofabinarytreeisstoredinanobjectofanewbinary_tree_nodeclassthatwearegoingtodefine

• Eachnodecontainsdataaswellaspointerstoitschildren(nodes)• Anentiretreeisrepresentedasapointertotherootnode

binary_tree_nodeClass

• variables• functions

template <class Item>class binary_tree_node{public:

......private:

Item data_field;binary_tree_node *left_field;binary_tree_node *right_field;

};

bintree

//retrievalsdataleftright//setset_dataset_leftset_right//booleanis_leaf

CreatingandManipulatingTrees

• Consideronlytwofunctions• Clearingatree

• Returnnodesofatree totheheap• Copyingatree

• TheImplementationiseasierthanitseems• ifweuserecursivethinking

ClearingaTree

Q

V

T

K S

AE

L

Root

Clear LEFT SUBTREE

ClearingaTree

V

S

A

L

Root

Clear RIGHT SUBTREE

ClearingaTree

VRoot

Return root node to the heap

ClearingaTree

NULL Root

Set the root pointer to NULL

ClearaTree

• key:recursivethinking

template <class Item>void tree_clear(binary_tree_node<Item>*& root_ptr)// Library facilities used: cstdlib{

if (root_ptr != NULL){

tree_clear( root_ptr->left( ) ); // clear left sub_treetree_clear( root_ptr->right( ) ); // clear right sub_treedelete root_ptr; // return root node to the heaproot_ptr = NULL; // set root pointer to the null

}}

bintree

CopyaTree

• Canyouimplementthecopy?(p467)

template <class Item>binary_tree_node<Item>* tree_copy(const binary_tree_node<Item>* root_ptr)// Library facilities used: cstdlib{

binary_tree_node<Item> *l_ptr;binary_tree_node<Item> *r_ptr;

if (root_ptr == NULL)return NULL;

else{

l_ptr = tree_copy( root_ptr->left( ) ); // copy the left sub_treer_ptr = tree_copy( root_ptr->right( ) ); // copy the right sub_treereturn

new binary_tree_node<Item>( root_ptr->data( ), l_ptr, r_ptr);} // copy the root node and set the the root pointer

}

bintree

BinaryTreeTraversals

• pre-order traversal• root(leftsub_tree) (right sub_tree)

• in-ordertraversal• (leftsub_tree) root(right sub_tree)

• post-order traversal• (leftsub_tree) (right sub_tree)root

• backwardin-ordertraversal• (right sub_tree)root (leftsub_tree)

bintree

PreorderTraversal:JEAHTMY

‘J’

‘E’

‘A’ ‘H’

‘T’

‘M’ ‘Y’

tree

Print left subtree second Print right subtree last

Print first

PreorderTraversal

• Example:printthecontentsofeachnode

template <class Item>void preorder_print(const binary_tree_node<Item>* node_ptr)// Library facilities used: cstdlib, iostream{

if (node_ptr != NULL){

std::cout << node_ptr->data( ) << std::endl;preorder_print(node_ptr->left( ));preorder_print(node_ptr->right( ));

}}

InorderTraversal:AEHJMTY

‘J’

‘E’

‘A’ ‘H’

‘T’

‘M’ ‘Y’

tree

Print left subtree first Print right subtree last

Print second

InorderTraversal

• Example:printthecontentsofeachnode

template <class Item>void inorder_print(const binary_tree_node<Item>* node_ptr)// Library facilities used: cstdlib, iostream{

if (node_ptr != NULL){

inorder_print(node_ptr->left( ));std::cout << node_ptr->data( ) << std::endl;inorder_print(node_ptr->right( ));

}}

Postorder Traversal: A H E M Y T J

‘J’

‘E’

‘A’ ‘H’

‘T’

‘M’ ‘Y’

tree

Print left subtree first Print right subtree second

Print last

PostorderTraversal

• Example:printthecontentsofeachnode

template <class Item>void postorder_print(const binary_tree_node<Item>* node_ptr)// Library facilities used: cstdlib, iostream{

if (node_ptr != NULL){

postorder_print(node_ptr->left( ));postorder_print(node_ptr->right( ));std::cout << node_ptr->data( ) << std::endl;

}}

BackwardInorderTraversal:YTMJHEA

‘J’

‘E’

‘A’ ‘H’

‘T’

‘M’ ‘Y’

tree

Print right subtree firstPrint left subtree last

Print second

BackwardInorderTraversal:YTMJHEA

Print right subtree first

Print left subtree last

Print second

AUsefulBackwardInorderTraversal

• Intenteachnumberaccordingitsdepth

template <class Item, class SizeType>void print(binary_tree_node<Item>* node_ptr, SizeType depth)// Library facilities used: iomanip, iostream, stdlib{

if (node_ptr != NULL){

print(node_ptr->right( ), depth+1);std::cout << std::setw(4*depth) << ""; // Indent 4*depth spaces.std::cout << node_ptr->data( ) << std::endl;print(node_ptr->left( ), depth+1);

}}

bintree

AChallengingQuestion:

• Forthetraversalswehaveseen,the“processing”wassimplyprintingthevaluesofthenode

•Butwe’dliketodoanykindofprocessing• Wecanreplace“cout”withsomeotherformof“processing”

•Buthowabout1000kinds?• Cantemplatebehelpful?

• Solution::::::::> (pages501– 507)

Aparametercanbeafunction

•writeonefunctioncapableofdoinganything•Aparametertoafunctionmaybeafunction.Suchaparameterisdeclaredby• thenameofthefunction’sreturntype(orvoid),• thenthenameoftheparameter(i.e.thefunction),• andfinallyapairofparentheses().• Inside()isalistofparametertypesofthatparameterfunction

• Example• intsum(voidf(int&,double),inti,...);

PreorderTraversal– printonly

• Example:printthecontentsofeachnode

template <class Item>void preorder_print(const binary_tree_node<Item>* node_ptr)// Library facilities used: cstdlib, iostream{

if (node_ptr != NULL){

std::cout << node_ptr->data( ) << std::endl;preorder_print(node_ptr->left( ));preorder_print(node_ptr->right( ));

}}

PreorderTraversal– generalform

• Atemplatefunctionfortreetraversals

template <class Item>void preorder(void f(Item&), binary_tree_node<Item>* node_ptr)// Library facilities used: cstdlib{

if (node_ptr != NULL){

f( node_ptr->data( ) ); // node_ptr->data() return reference !preorder(f, node_ptr->left( ));preorder(f, node_ptr->right( ));

}}

PreorderTraversal– howtouse

• Definearealfunctionbeforecalling

void printout(int & it)// Library facilities used: iostream

{std::cout << it << std::endl;

}

Can you print out all the node of a tree pointed by root ?

binary_tree_node<int> *root; ....preorder(printout, root); Yes!!!

PreorderTraversal– anotherfunctions

• Candefineotherfunctions...

void assign_default(int& it)// Library facilities used: iostream

{it = 0;

} // unfortunately template does not work here for function parameters

You can assign a default value to all the node of a tree pointed by root:

binary_tree_node<int> *root; ....preorder(assign_default, root);

PreorderTraversal– howtouse

• Canthefunction-argumentsbetemplate?

template <class Item>void printout(Item& it)// Library facilities used: iostream

{std::cout << it << std::endl;

}

Can you print out all the node of a tree pointed by root ?

binary_tree_node<string> *root; ....preorder(print_out, root); X ! print_out should have real types

PreorderTraversal– howtouse

• Thefunction-argumentsmaybetemplateif...

template <class Item>void printout(Item& it)// Library facilities used: iostream

{std::cout << it << std::endl;

}

Can you print out all the node of a tree pointed by root ?

binary_tree_node<string> *root; ....preorder(print_out<string>, root);

But you may do the instantiation like this

PreorderTraversal– amoregeneralform

• Anextremelygeneralimplementation(p505)

template <class Process, class BTNode>void preorder(Process f, BTNode* node_ptr)

// Note: BTNode may be a binary_tree_node or a const binary tree node.// Process is the type of a function f that may be called with a single// Item argument (using the Item type from the node),// as determined by the actual f in the following.// Library facilities used: cstdlib

{if (node_ptr != NULL){

f( node_ptr->data( ) );preorder(f, node_ptr->left( ));preorder(f, node_ptr->right( ));

}}

bintree

FunctionsasParameters

• WecandefineatemplatefunctionX withfunctionsasparameters– whicharecalledfunctionparameters

• AfunctionparametercanbesimplywrittenasProcessf(whereProcessisatemplate),andtheformsandnumberofparametersforf aredeterminedbytheactualcalloffinsidethetemplatefunctionX

• TherealfunctionargumentforfwhencallingthethetemplatefunctionX cannotbeatemplatefunction,itmustbeinstantiatedinadvanceorrightinthefunctioncall

Summary

• Tree,BinaryTree,CompleteBinaryTree• child,parent,sibling,root,leaf,ancestor,...

•ArrayRepresentationforCompleteBinaryTree• Difficultifnotcompletebinarytree

•AClassofbinary_tree_node• eachnodewithtwolinkfields

• TreeTraversals• recursivethinkingmakesthingsmucheasier

•AgeneralTreeTraversal• AFunctionasaparameterofanotherfunction

THE END

Presentation copyright 1997 Addison Wesley Longman,For use with Data Structures and Other Objects Using C++by Michael Main and Walter Savitch.

Some artwork in the presentation is used with permission from Presentation Task Force(copyright New Vision Technologies Inc) and Corel Gallery Clipart Catalog (copyrightCorel Corporation, 3G Graphics Inc, Archive Arts, Cartesia Software, Image ClubGraphics Inc, One Mile Up Inc, TechPool Studios, Totem Graphics Inc).

Students and instructors who use Data Structures and Other Objects Using C++ are welcometo use this presentation however they see fit, so long as this copyright notice remainsintact.

Copyright from slide 2 – slide 49:

top related