lecture 15 trees and tree traversals -...

90
CSC212 Data Structure - Section FG Lecture 15 Trees and Tree Traversals Instructor: Feng HU Department of Computer Science City College of New York

Upload: others

Post on 17-Jul-2020

17 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

CSC212 Data Structure - Section FG

Lecture15TreesandTreeTraversals

Instructor:FengHUDepartmentofComputerScience

CityCollegeofNewYork

Page 2: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

Motivation

• Linearstructures• arrays• dynamicarrays• linkedlists

• NonlinearStructures• trees- HierarchicalStructures• Graphs

• Why???

Page 3: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

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 ?

Page 4: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

ATreeforallthemailingaddresses

China

Earth

USA... ...Korea

NY... ...

... ...

NYC

MA ... ...

CCNY

F. HU

Albany

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

... ...

... ...

CS

Page 5: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

TreesandBinaryTrees

•Chapter10introducestrees.• Thispresentationillustratesbasicterminologyforbinarytrees

• andfocuseson• CompleteBinaryTrees:thesimplestkindoftrees

• BinaryTreeTraversals:anykindofbinarytrees

Data Structuresand Other ObjectsUsing C++

Page 6: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

BinaryTrees

•Abinarytreehasnodes,similartonodesinalinkedliststructure.

•Data ofonesortoranothermaybestoredateachnode.

•Butitistheconnections betweenthenodeswhichcharacterizeabinarytree.

Page 7: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

BinaryTrees

•Abinarytreehasnodes,similartonodesinalinkedliststructure.

•Data ofonesortoranothermaybestoredateachnode.

•Butitisthe connections betweenthenodeswhichcharacterizeabinarytree.

An example canillustrate how theconnections work

Page 8: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

ABinaryTreeofStates

Inthisexample,thedatacontainedateachnodeisoneofthe50states.

Washington

Colorado

Oklahoma

Arkansas

Mass.

New

Ham

pshi

re

Arizona

Nebraska

Page 9: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

ABinaryTreeofStates

Eachtreehasaspecialnodecalleditsroot,usuallydrawnatthetop.

Washington Arkansas Colorado Florida Oklahoma Arizona Mass. NewHampshire Nebraska

Page 10: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

ABinaryTreeofStates

Eachtreehasaspecialnodecalleditsroot,usuallydrawnatthetop. The example tree

has Washingtonas its root.

Washington Arkansas Colorado Florida Oklahoma Arizona Mass. NewHampshire Nebraska

Page 11: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

ABinaryTreeofStates

Eachnodeispermittedtohavetwolinkstoothernodes,calledtheleftchild andtherightchild.

Washington Arkansas Colorado Florida Oklahoma Arizona Mass. NewHampshire Nebraska

Page 12: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

ABinaryTreeofStates

Eachnodeispermittedtohavetwolinkstoothernodes,calledtheleftchild andtherightchild.

Washington Arkansas Colorado Florida Oklahoma Arizona Mass. NewHampshire Nebraska

Page 13: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

ABinaryTreeofStates

Childrenareusuallydrawnbelowanode.

The right child ofWashington is

Colorado.

The left child ofWashington is

Arkansas.

Washington Arkansas Colorado Florida Oklahoma Arizona Mass. NewHampshire Nebraska

Page 14: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

ABinaryTreeofStates

Somenodeshaveonlyonechild.

Arkansas has aleft child, but no

right child.

Washington Arkansas Colorado Florida Oklahoma Arizona Mass. NewHampshire Nebraska

Page 15: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

AQuiz

Somenodeshaveonlyonechild.

Which node hasonly a right child?

Washington Arkansas Colorado Florida Oklahoma Arizona Mass. NewHampshire Nebraska

Page 16: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

AQuiz

Somenodeshaveonlyonechild.

Florida hasonly a right child.

Washington Arkansas Colorado Florida Oklahoma Arizona Mass. NewHampshire Nebraska

Page 17: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

ABinaryTreeofStates

Anodewithnochildreniscalledaleaf.

Washington Arkansas Colorado Florida Oklahoma Arizona Mass. NewHampshire Nebraska

Page 18: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

ABinaryTreeofStates

Eachnodeiscalledtheparent ofitschildren.

Washington is theparent of Arkansas

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

Hampshire Nebraska

Page 19: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

ABinaryTreeofStates

Tworulesaboutparents:

❶ The root has no parent.

❷ Every other node has exactly one parent.

Washington Arkansas Colorado Florida Oklahoma Arizona Mass. NewHampshire Nebraska

Page 20: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

ABinaryTreeofStates

Twonodeswiththesameparentarecalledsiblings.

Arkansasand Coloradoare siblings.

Washington Arkansas Colorado Florida Oklahoma Arizona Mass. NewHampshire Nebraska

Page 21: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

CompleteBinaryTrees

Acompletebinarytreeisaspecialkindofbinarytreewhichwillbeusefultous.

Page 22: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

CompleteBinaryTrees

Acompletebinarytreeisaspecialkindofbinarytreewhichwillbeusefultous.

When a completebinary tree is built,

its first node must bethe root.

Page 23: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

CompleteBinaryTrees

Thesecondnodeofacompletebinarytreeisalwaystheleftchildoftheroot...

Page 24: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

CompleteBinaryTrees

Thesecondnodeofacompletebinarytreeisalwaystheleftchildoftheroot......andthethirdnodeisalwaystherightchildoftheroot.

Page 25: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

CompleteBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright.

Page 26: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

CompleteBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright.

Page 27: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

CompleteBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright.

Page 28: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

CompleteBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright.

Page 29: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

CompleteBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright.

Page 30: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

CompleteBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright.

Page 31: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

IsThisComplete?

Page 32: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

IsThisComplete?

Page 33: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

IsThisComplete?

Page 34: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

IsThisComplete?

Page 35: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

IsThisComplete?

Yes!✔ Itiscalledtheemptytree,andit

hasnonodes,notevenaroot.

Page 36: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

FullBinaryTrees

Afullbinarytreeisaspecialkindofcompletebinarytree

When a fullbinary tree is built,

its first node must bethe root.

FULL

Page 37: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

FullBinaryTrees

Thesecondnodeofafullbinarytreeisalwaystheleftchildoftheroot...

not FULL yet

Page 38: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

FullBinaryTrees

Thesecondnodeofafullbinarytreeisalwaystheleftchildoftheroot......andyouMUSThavethethirdnodewhichalwaystherightchildoftheroot. FULL

Page 39: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

FullBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright.

not FULL yet

Page 40: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

FullBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright.

not FULL yet

Page 41: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

FullBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright.

not FULL yet

Page 42: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

FullBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright...untileveryleafhasthesamedepth(2)

FULL!

Page 43: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

FullBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright.

Page 44: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

FullBinaryTrees

Thenextnodesmustalwaysfillthenextlevelfromlefttoright.

Page 45: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

IsThisFull?

Page 46: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

IsThisFull?

Page 47: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

IsThisFull?

Page 48: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

IsThisFull?

Page 49: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

IsThisFull?

Yes!✔ Itiscalledtheemptytree,andit

hasnonodes,notevenaroot.

Page 50: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

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

Page 51: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

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.

Page 52: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

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

Page 53: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

BinaryTreeSummary

•Binarytreescontainnodes.• Eachnodemayhavealeftchildandarightchild.• Ifyoustartfromanynodeandmoveupward,youwilleventuallyreachtheroot.

• Everynodeexcepttheroothasoneparent.Theroothasnoparent.

•Completebinarytreesrequirethenodestofillineachlevelfromleft-to-rightbeforestartingthenextlevel.

Page 54: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

BinaryTreeBasics

Abinarytreeisastructureinwhich:

Eachnodecanhaveatmosttwochildren,andinwhichauniquepathexistsfromtheroottoeveryothernode.

Thetwochildrenofanodearecalledtheleftchild andtherightchild, iftheyexist.

Page 55: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

ABinaryTreeExercise

Q

V

T

K S

AE

L

Page 56: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

Howmanyleafnodes?

Q

V

T

K S

AE

L

Page 57: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

HowmanydescendantsofQ?

Q

V

T

K S

AE

L

Page 58: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

HowmanyancestorsofK?

Q

V

T

K S

AE

L

Question: How to implement a general binary tree ?

Page 59: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

ImplementingaBinaryTreewithaClassforNodes

Q

V

T

K S

AE

L

Root

Page 60: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

BinaryTreeNodes

• Eachnodeofabinarytreeisstoredinanobjectofanewbinary_tree_nodeclassthatwearegoingtodefine

• Eachnodecontainsdataaswellaspointerstoitschildren(nodes)• Anentiretreeisrepresentedasapointertotherootnode

Page 61: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

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

Page 62: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

CreatingandManipulatingTrees

• Consideronlytwofunctions• Clearingatree

• Returnnodesofatree totheheap• Copyingatree

• TheImplementationiseasierthanitseems• ifweuserecursivethinking

Page 63: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

ClearingaTree

Q

V

T

K S

AE

L

Root

Clear LEFT SUBTREE

Page 64: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

ClearingaTree

V

S

A

L

Root

Clear RIGHT SUBTREE

Page 65: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

ClearingaTree

VRoot

Return root node to the heap

Page 66: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

ClearingaTree

NULL Root

Set the root pointer to NULL

Page 67: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

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

Page 68: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

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

Page 69: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

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

Page 70: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

PreorderTraversal:JEAHTMY

‘J’

‘E’

‘A’ ‘H’

‘T’

‘M’ ‘Y’

tree

Print left subtree second Print right subtree last

Print first

Page 71: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

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

}}

Page 72: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

InorderTraversal:AEHJMTY

‘J’

‘E’

‘A’ ‘H’

‘T’

‘M’ ‘Y’

tree

Print left subtree first Print right subtree last

Print second

Page 73: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

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

}}

Page 74: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

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

Page 75: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

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;

}}

Page 76: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

BackwardInorderTraversal:YTMJHEA

‘J’

‘E’

‘A’ ‘H’

‘T’

‘M’ ‘Y’

tree

Print right subtree firstPrint left subtree last

Print second

Page 77: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

BackwardInorderTraversal:YTMJHEA

Print right subtree first

Print left subtree last

Print second

Page 78: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

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

Page 79: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

AChallengingQuestion:

• Forthetraversalswehaveseen,the“processing”wassimplyprintingthevaluesofthenode

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

•Buthowabout1000kinds?• Cantemplatebehelpful?

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

Page 80: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

Aparametercanbeafunction

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

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

Page 81: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

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

}}

Page 82: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

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

}}

Page 83: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

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

Page 84: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

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

Page 85: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

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

Page 86: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

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

Page 87: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

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

Page 88: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

FunctionsasParameters

• WecandefineatemplatefunctionX withfunctionsasparameters– whicharecalledfunctionparameters

• AfunctionparametercanbesimplywrittenasProcessf(whereProcessisatemplate),andtheformsandnumberofparametersforf aredeterminedbytheactualcalloffinsidethetemplatefunctionX

• TherealfunctionargumentforfwhencallingthethetemplatefunctionX cannotbeatemplatefunction,itmustbeinstantiatedinadvanceorrightinthefunctioncall

Page 89: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

Summary

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

•ArrayRepresentationforCompleteBinaryTree• Difficultifnotcompletebinarytree

•AClassofbinary_tree_node• eachnodewithtwolinkfields

• TreeTraversals• recursivethinkingmakesthingsmucheasier

•AgeneralTreeTraversal• AFunctionasaparameterofanotherfunction

Page 90: Lecture 15 Trees and Tree Traversals - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture15-Trees.pdfData Structures and Other Objects Using C++. Binary Trees •A binary tree has nodes,

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: