Tree Traversing

advertisement
Traversing Trees
Traversing a Tree
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
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
Visit the node
T
Then, visit the left sub tree
recursively
v 75
v 60
58
75
60 58
80
65 v 77
65 80 77 92
92
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
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 )
Visit the left sub tree recursively
T
Done with or No left sub tree?
75
60
58
Then, visit the right sub tree
recursively
80
65
78
92
58 65 60 78 92 80 75
Done with or No right sub tree?
NOW, visit the node
Then go back to the calling function
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
 Another
way to make sure that we visit every node is with
LVR (a node is visited after its left descendants but before
Visit the left sub tree recursively
its right ones)
T
Done with or No left sub tree?
NOW, visit the node
75
60
58
80
65
78
Then, visit the right sub tree recursively
92
58 60 65 75 78 80 92
Done with or No right sub tree?
Then go back to the calling function
Download