22.02.2014 Views

Discrete Mathematics University of Kentucky CS 275 Spring ... - MGNet

Discrete Mathematics University of Kentucky CS 275 Spring ... - MGNet

Discrete Mathematics University of Kentucky CS 275 Spring ... - MGNet

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Definition (Postorder Traversal): Let T be an ordered rooted tree with root r. If T<br />

consists only <strong>of</strong> r, then r is the postorder traversal <strong>of</strong> T. Otherwise, suppose T 1 ,<br />

T 2 , …, T n are subtrees at r from left to right in T. Then the postorder traversal<br />

begins by traversing T 1 in postorder, T 2 in postorder, …, T n in postorder, and r.<br />

Example: In the tree example at the top <strong>of</strong> page 199, the postorder traversal<br />

order is 1.1, 1, 2.1, 2.2.1, 2.2, 2.3, 2, and 0.<br />

Notation: Let add_to_list(v) be a global function to append a vertex v to a list.<br />

The list must be initialized to / at some point before use.<br />

Note: The tree traversal algorithms are all easily defined recursively using a<br />

global list that must be initialized first.<br />

201<br />

procedure preorder_traversal( T: ordered rooted tree )<br />

r := root(T)<br />

add_to_list(r)<br />

for each child c <strong>of</strong> r from left to right<br />

T(c) := subtree with c as its root<br />

preorder_traversal( T(c) )<br />

procedure inorder_traversal( T: ordered rooted tree )<br />

r := root(T)<br />

if r = leaf then add_to_list(r)<br />

else<br />

q := first child <strong>of</strong> r from left to right<br />

T(q) := subtree with q as its root<br />

inorder( T(q) )<br />

add_to_list(r)<br />

for each remaining child c <strong>of</strong> r from left to right<br />

T(c) := subtree with c as its root<br />

inorder_traversal( T(c) )<br />

202

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!