Download presentation
Presentation is loading. Please wait.
Published byMatthew Quinn Modified over 8 years ago
1
Traversing Trees
2
Traversing is the systematic way of accessing, or ‘visiting’ all the nodes in a tree. Consider the three operations: V: Visit a node L: (Recursively) traverse the left subtree of a node R: (Recursively) traverse the right subtree of a node Traversing a Tree
3
Tree Traversing We can traverse a tree in six different orders: LVR VLR LRV VRL RVL RLV
4
Preorder Traversal Algorithm preorder( T, v ) perform the visit action for node v for each child w of v do recursively traverse the subtree rooted at w by calling preorder( T, w ) void preorderPrint(const Tree& T, const Position& v ) { cout << v.element() << " "; PositionIterator children = T.children(v); while( children.hasNext() ) { preorderPrint( T, children.next() ) }
5
Preorder Traversal One way to make sure that we visit every node is with VLR ( a node is visited before its descendants ) Start by visiting the root Then traverse each subtree 75 77 80 925865 60 T v v v Visit the node Then, visit the left sub tree recursively Done with or No left sub tree? Then, visit the right sub tree recursively 75605865807792 Done with or No right sub tree? Then go back to the calling function
6
Postorder Traversal Algorithm postorder( T, v ) for each child w of v do recursively traverse the subtree rooted at w by calling postorder( T, w ) perform the visit action for node v void postorderPrint(const Tree& T, const Position& v ){ PositionIterator children = T.children(v); while( children.hasNext() ) { postorderPrint( T, children.next() ) } cout << v.element() << " "; }
7
Postorder Traversal 75 78 80 9258 65 60 T Another way to make sure that we visit every node is with LRV, where you start by visiting each subtree, and then visit the node ( a node is visited after its descendants ) 58656078928075 NOW, visit the node Then go back to the calling function Visit the left sub tree recursively Done with or No left sub tree? Then, visit the right sub tree recursively Done with or No right sub tree?
8
Inorder Traversal Algorithm inorder( T, v ) { if v is an internal node then inorder ( T, T.leftChild(v) ) perform the visit action for node v if v is an internal node then inorder ( T, T.rightChild(v) ) }
9
Inorder Traversal 75 78 80 925865 60 T Another way to make sure that we visit every node is with LVR (a node is visited after its left descendants but before its right ones) 58606575788092 NOW, visit the node Visit the left sub tree recursively Done with or No left sub tree? Then, visit the right sub tree recursively Done with or No right sub tree? Then go back to the calling function
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.