Salta al contenuto
Note per Studenti Tree Traversals Report

Tree Traversals

In questa pagina 8

A traversal of a tree TT is a systematic scan of all the nodes of TT, 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     G

With 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 u,vu, v on the same level: uu is to the left of vv (and vv to the right of uu) if uu appears before vv 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 nn be the number of nodes of TT. 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 u∈Tu \in T, so the recursion tree has nn nodes.

  • Cost per node: the call on uu costs, excluding recursive calls,

    1. the visit of uu, taking tut_u (depends on the action performed);
    2. scanning (not visiting) the children of uu: proportional to cuc_u, the number of children;
    3. the recursive calls, accounted for in the subcalls.

    So the cost per node is Θ(cu+1+tu)\Theta(c_u + 1 + t_u). The +1+1 makes explicit that even a leaf has non-zero cost.

  • Total, since there is one call per node: Θ(∑u∈T(cu+1+tu))=Θ(∑u∈T(cu+1)+∑u∈Ttu)=Θ(n+∑u∈Ttu),\Theta\Big(\sum_{u \in T} (c_u + 1 + t_u)\Big) = \Theta\Big(\sum_{u \in T} (c_u + 1) + \sum_{u \in T} t_u\Big) = \Theta\Big(n + \sum_{u \in T} t_u\Big), because ∑u∈T(cu+1)=(n−1)+n=2n−1\sum_{u \in T} (c_u + 1) = (n - 1) + n = 2n - 1 by Proposition 8.4 (∑ucu=n−1\sum_u c_u = n - 1).

  • In general the cost is Θ(n+∑utu)\Theta(n + \sum_{u} t_u).

  • If tu=O(1)t_u = O(1) for every node, the traversal runs in Θ(n)\Theta(n).

  • 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 vv 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 vv its depth in a field v.depth, in a time analysed as a function of nn.

Idea. Modify preorder: the visit of vv computes its depth assuming the depths of all its ancestors are already stored. If vv 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 Θ(n+∑utu)\Theta(n + \sum_u t_u). The visit is Θ(1)\Theta(1) (reads one field of the parent, access to the parent and to a field are constant), so the total is Θ(n)\Theta(n).

Calling depth() on every node instead would cost Ω(n2)\Omega(n^2) 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 vv has a field v.loc-size, the space occupied by that node alone (excluding its descendants). Compute for each node vv the total space of TvT_v 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 vv. 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, Θ(n+∑utu)\Theta(n + \sum_u t_u). The visit (summing the children's sizes, adding loc-size) is Θ(1)\Theta(1), so the total is Θ(n)\Theta(n).

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).
  • uu is to the left of vv (same level) if uu comes before vv 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 Θ(cu+1+tu)\Theta(c_u + 1 + t_u), so total Θ(n+∑u∈Ttu),\Theta\Big(n + \sum_{u \in T} t_u\Big), using ∑u(cu+1)=2n−1\sum_u (c_u + 1) = 2n - 1 (Proposition 8.4). With O(1)O(1) visits it is Θ(n)\Theta(n). Postorder is analogous.

  • AllDepths (preorder): v.depth <- 0 for the root, else 1 + parent.depth, then recurse on the children. Θ(n)\Theta(n); calling depth() on every node would be Ω(n2)\Omega(n^2) on a chain.
  • DiskSpace (postorder): s = sum of the recursive results over the children, v.aggr-size <- v.loc-size + s, return it. Θ(n)\Theta(n).

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 →.

Teoria collegata