Traversing Trees
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
Tree Traversing We can traverse a tree in six different orders: LVR VLR LRV VRL RVL RLV
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() ) }
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 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 Done with or No right sub tree? Then go back to the calling function
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() << " "; }
Postorder Traversal 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 ) 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?
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) ) }
Inorder Traversal 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) 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