Tree Traversals
In questa pagina 8
A traversal of a tree is a systematic scan of all the nodes of , performing some operation (the visit) at each node. Traversals are an algorithmic design pattern: a general scheme that can be instantiated to compute values or to set variables associated with nodes. The children are enumerated by the iterator of children(v) (see Trees - Definitions and PropertiesA rooted tree is a hierarchy of nodes under a single root; depth is the distance from the root, height the distance from the farthest leaf, and the height of a tree equals the depth of its deepest leaf.Trees - Definitions and Properties →); examples assume left-to-right order.
For general trees there are two traversals:
- Preorder: visit the parent first, then (recursively) the subtrees rooted at its children. The work on a node may depend on what was done on its ancestors.
- Postorder: visit (recursively) the subtrees rooted at the children first, then the parent. The work on a node may depend on what was done on its descendants.
Preorder
Algorithm: preorder(T, v)
Input: node v in T
Output: visit of all nodes in the subtree T_v
visit(v);
foreach w in T.children(v) do
preorder(T, w);Initial call for the whole tree: preorder(T, T.root()).
Each node is processed before its descendants: top-down exploration. Base case: a leaf has no children, so after visiting it the function returns.
Postorder
Algorithm: postorder(T, v)
Input: node v in T
Output: visit of all nodes in the subtree T_v
foreach w in T.children(v) do
postorder(T, w);
visit(v);Initial call: postorder(T, T.root()).
Each node is processed after its descendants: bottom-up exploration. Same base case.
Example
A
/ | \
B C D
/ \ \
E F GWith children scanned left to right:
- preorder: A, B, E, F, C, D, G
- postorder: E, F, B, C, G, D, A
The order depends on the iterator used in the foreach.
Left of. For an ordered tree, two nodes on the same level: is to the left of (and to the right of ) if appears before in the preorder traversal. This matches the usual left-to-right drawing when the iterator scans children left to right.
Table of contents of a book (tree: book, chapters, sections): use preorder, since a chapter must be printed before its sections. Output: Book, Chapter 1, Section 1.1, Section 1.2, Section 1.2.1, Section 1.2.2, Chapter 2, Section 2.1, Section 2.2, Section 2.2.1, Section 2.2.2. Same for printing a file system as folders and files.
Complexity of a traversal
Let be the number of nodes of . Analyse preorder(T, T.root()) with its recursion tree (the algorithm calls itself on each child, then on the children of those, and so on).
Number of nodes: exactly one call for each node , so the recursion tree has nodes.
Cost per node: the call on costs, excluding recursive calls,
- the visit of , taking (depends on the action performed);
- scanning (not visiting) the children of : proportional to , the number of children;
- the recursive calls, accounted for in the subcalls.
So the cost per node is . The makes explicit that even a leaf has non-zero cost.
Total, since there is one call per node: because by Proposition 8.4 ().
In general the cost is .
If for every node, the traversal runs in .
The analysis of postorder is the same (same recursive structure, same cost per node).
Traversal as a design pattern
The traversal says when each node contributes, depending on its position in the tree:
- Preorder: the contribution of a node is computed before visiting its descendants, so it may depend on its ancestors. Top-down: propagation or initialisation.
- Postorder: the contribution is computed after visiting the descendants, so it may depend on their results. Bottom-up: aggregation or computation from the children.
The height(T, v) algorithm is already of this kind: the height of needs the heights of its children first, hence postorder.
For a binary tree there is a third traversal, see Binary Tree Traversals and Expression TreesInorder visits the left subtree, the node, then the right subtree; on the parse tree of an arithmetic expression postorder evaluates the expression and inorder rebuilds the fully parenthesized infix form, both in linear time.Binary Tree Traversals and Expression Trees →.
Preorder example: AllDepths
Problem. Store in each node its depth in a field v.depth, in a time analysed as a function of .
Idea. Modify preorder: the visit of computes its depth assuming the depths of all its ancestors are already stored. If is the root, v.depth = 0; otherwise v.depth = 1 + parent(v).depth (the parent was visited before).
Algorithm: AllDepths(T, v)
Input: node v in T (the parent of v, if it exists, already has its depth field set)
Output: all nodes of the subtree T_v have their depth field set
if (T.isRoot(v)) then v.depth <- 0
else v.depth <- 1 + T.parent(v).depth
foreach w in T.children(v) do AllDepths(T, w)First call: AllDepths(T, T.root()). It returns nothing, it only sets the fields. The if is the visit, the foreach the recursive calls on the children.
Complexity. Same structure as preorder, so . The visit is (reads one field of the parent, access to the parent and to a field are constant), so the total is .
Calling depth() on every node instead would cost in the worst case, since each call costs proportionally to the node's depth (e.g. a chain).
Postorder example: DiskSpace
Problem. A file system is a tree: internal nodes are directories, leaves are files. Each node has a field v.loc-size, the space occupied by that node alone (excluding its descendants). Compute for each node the total space of and store it in v.aggr-size.
Idea. Postorder: first the occupancy of the children, then that of the parent. (Note: the aggregated size includes the node's own loc-size.)
Algorithm: DiskSpace(T, v)
Input: node v in T, field loc-size set for all nodes in T
Output: aggregated space of T_v = sum over u in T_v of u.loc-size, and
update of u.aggr-size for each u in T_v with the aggregated space of T_u
s <- 0;
foreach w in T.children(v) do
s <- s + DiskSpace(T, w);
v.aggr-size <- v.loc-size + s;
return v.aggr-size;First call: DiskSpace(T, T.root()). The foreach is the recursive visit of the children, the last two lines are the visit of . The value returned by each recursive call is used (it is added to s); otherwise it would be lost.
Complexity. Same recursive structure as postorder, . The visit (summing the children's sizes, adding loc-size) is , so the total is .
Remarks on writing recursive algorithms
- A recursive algorithm may use global variables, which persist during the whole execution, and local variables, which exist only for one call.
- Values returned by recursive calls must be used, or they are lost.
Versione ripasso
A traversal visits every node once, doing a visit(v) at each. It is an algorithmic design pattern.
preorder(T, v): visit(v); foreach w in T.children(v): preorder(T, w)
postorder(T, v): foreach w in T.children(v): postorder(T, w); visit(v)Initial call on T.root(). Base case: a leaf (no children, no recursive calls).
- Preorder = top-down: a node's work may depend on its ancestors (propagation, initialisation; table of contents, file system listing).
- Postorder = bottom-up: a node's work may depend on its descendants (aggregation;
height). - Example tree: root A with children B, C, D; B has E, F; D has G. Preorder A, B, E, F, C, D, G. Postorder E, F, B, C, G, D, A (left-to-right children).
- is to the left of (same level) if comes before in preorder.
- Exercise pattern: in postorder the last node is the root, in preorder the first. Given preorder A B C D E F and postorder C D B F E A, the tree is A with children B (leaves C, D) and E (leaf F).
Complexity. One call per node, cost per call , so total using (Proposition 8.4). With visits it is . Postorder is analogous.
- AllDepths (preorder):
v.depth <- 0for the root, else1 + parent.depth, then recurse on the children. ; callingdepth()on every node would be on a chain. - DiskSpace (postorder):
s= sum of the recursive results over the children,v.aggr-size <- v.loc-size + s, return it. .
Typical mistakes: dropping the returned value of a recursive call; using preorder when the node needs its children's results (or the reverse); forgetting that the child order depends on the iterator.
See Trees - Definitions and PropertiesA rooted tree is a hierarchy of nodes under a single root; depth is the distance from the root, height the distance from the farthest leaf, and the height of a tree equals the depth of its deepest leaf.Trees - Definitions and Properties → and Binary Tree Traversals and Expression TreesInorder visits the left subtree, the node, then the right subtree; on the parse tree of an arithmetic expression postorder evaluates the expression and inorder rebuilds the fully parenthesized infix form, both in linear time.Binary Tree Traversals and Expression Trees →.