Salta al contenuto
Note per Studenti Binary Tree Traversals and Expression Trees Report

Binary Tree Traversals and Expression Trees

In questa pagina 3

For binary trees, besides preorder and postorder (see Tree TraversalsPreorder visits a node before its subtrees (top-down), postorder after them (bottom-up); both run in time proportional to the number of nodes plus the cost of the visits, and are design patterns for algorithms on trees.Tree Traversals →), there is the inorder traversal:

  1. recursively visit the left subtree,
  2. then visit the parent,
  3. then recursively visit the right subtree.

Inorder traversal

Algorithm: inorder(T, v)
Input:  node v in T
Output: visit (inorder) of all nodes in the subtree T_v
if (T.left(v) != null) then inorder(T, T.left(v))
visit(v);
if (T.right(v) != null) then inorder(T, T.right(v))

Initial call: inorder(T, T.root()).

Complexity: Θ(n+∑u∈Ttu)\Theta(n + \sum_{u \in T} t_u), where nn is the number of nodes and tut_u the time of the visit of uu. Same analysis as preorder and postorder.

Example. On a binary search tree (studied later) the inorder traversal visits the elements in increasing order:

        5
      /   \
     3     7
    / \   / \
   2   4 6   8

inorder: 2, 3, 4, 5, 6, 7, 8

Arithmetic expressions

A binary operator acts on two operands: ++, −-, ∗*, ÷\div. In 3+53 + 5 the operator ++ combines the operands 3 and 5.

In infix notation each binary operator is written between its two operands: 3+53 + 5, x∗yx * y, a−(b/c)a - (b / c).

A fully parenthesized expression in infix notation is:

  • a constant or variable aa, or
  • (E1 Op E2)(E_1 \ \text{Op}\ E_2), where E1,E2E_1, E_2 are fully parenthesized expressions in infix notation and Op is a binary operator.

Parentheses make the evaluation order explicit, independently of operator precedence. Example: ((15+x)∗(7−(9÷3)))((15 + x) * (7 - (9 \div 3))).

Parse tree

The parse tree TT of an arithmetic expression EE (binary operators only) is a proper binary tree whose leaves contain the constants or variables of EE and whose internal nodes contain the operators of EE:

  • if E=aE = a (constant or variable), TT is a single leaf containing aa;
  • if E=(E1 Op E2)E = (E_1 \ \text{Op}\ E_2), the root of TT contains Op, and its left (right) subtree is the parse tree of E1E_1 (E2E_2).

Parse tree of ((15+x)∗(7−(9÷3)))((15 + x) * (7 - (9 \div 3))):

            *
          /   \
        +       -
       / \     / \
     15   x   7   ÷
                 / \
                9   3

The parentheses are implicit in the structure of the tree.

Remarks:

  • The parse tree is proper because the operators are binary. With unary operators (e.g. −15∗3+7-15 * 3 + 7) it is no longer proper.
  • In compilers, a postorder traversal gives the postfix notation (reverse Polish notation: operands first, then operators), easily evaluated at run time with a stack. Here: 15 x + 7 9 3 ÷ - *. Type checking, verification and optimisation work on the parse tree.

Evaluation: postorder

A postorder traversal evaluates the expression directly on the parse tree, without converting to postfix.

Algorithm: evaluateExpression(T, v)
Input:  parse tree T for E, node v in T
Output: value of the expression E_v associated to the subtree T_v
if T.isInternal(v) then
    x <- evaluateExpression(T, T.left(v));
    y <- evaluateExpression(T, T.right(v));
    op <- v.getElement();
    return x op y;
else return v.getElement();

The recursive calls on the two subtrees come first, then the visit of vv (take the operator, apply it to the children's values). Initial call: evaluateExpression(T, T.root()).

Example above: with x=1x = 1, (15+1)∗(7−9÷3)=16∗4=64(15 + 1) * (7 - 9 \div 3) = 16 * 4 = 64 (the value given in the slides).

Complexity with vv = root: Θ(n)\Theta(n), where nn is the number of nodes of TT, i.e. the number of constants, variables and operators of EE. It is the postorder analysis: the visit takes Θ(1)\Theta(1), assuming the operator is applied in constant time.

Generation of the expression: inorder

An inorder traversal rebuilds the fully parenthesized infix expression from the parse tree.

Algorithm: infix(T, v)
Input:  parse tree T for E, node v in T
Output: print the expression E_v associated to the subtree T_v
if T.isExternal(v) then
    print v.getElement();
else
    print '(' + infix(T, T.left(v)) + v.getElement() + infix(T, T.right(v)) + ')';

Left subtree first, then the node (the operator), then the right subtree. Initial call: infix(T, T.root()).

Complexity with vv = root: Θ(n)\Theta(n), nn = number of constants, variables and operators of EE. Same analysis as inorder, with constant-cost visits.

Exercise: heightSum

The heightsum of a proper binary tree TT is the sum of the heights of all its nodes (leaf: height 0; internal node: 1 + the maximum height of its children). Design a recursive heightSum(T, v) computing the heightsum of TvT_v, and analyse heightSum(T, T.root()) in terms of nn.

Naive idea. At an internal node vv with children u,wu, w: heightSum(Tv)=heightSum(Tu)+heightSum(Tw)+height(Tv).\text{heightSum}(T_v) = \text{heightSum}(T_u) + \text{heightSum}(T_w) + \text{height}(T_v). Problem: if the height of vv is not obtained recursively, computing it requires visiting all the nodes of TvT_v again.

Idea. Postorder pattern, returning not only the sum of the heights in TvT_v but also the height of vv itself. Otherwise, after the recursive calls on the children, the height of vv (and so the heightsum of TvT_v) could not be determined.

Algorithm: heightSum(T, v)
Input:  proper binary tree T, node v in T
Output: sum of the heights of the nodes in T_v; height of v
if T.isExternal(v) then return (0, 0)
(sL, hL) <- heightSum(T, T.left(v))
(sR, hR) <- heightSum(T, T.right(v))
h <- max{hL, hR} + 1
s <- sL + sR + h
return (s, h)

Base case: a leaf returns (0,0)(0, 0) (heightsum 0, height 0). Postorder: recursive calls on the left and right subtrees first, then the visit of vv computes its height h and its heightsum s. Initial call: heightSum(T, T.root()).

Complexity: Θ(n)\Theta(n). Same analysis as postorder, with Θ(1)\Theta(1) cost per visit.

Lesson: to design an efficient algorithm it is sometimes useful to compute information richer than what is requested; here the height in addition to the sum of heights.

Versione ripasso

Inorder: left subtree, then the node, then right subtree.

inorder(T, v):
  if T.left(v) != null: inorder(T, T.left(v))
  visit(v)
  if T.right(v) != null: inorder(T, T.right(v))

Complexity Θ(n+∑utu)\Theta(n + \sum_u t_u), same analysis as Tree TraversalsPreorder visits a node before its subtrees (top-down), postorder after them (bottom-up); both run in time proportional to the number of nodes plus the cost of the visits, and are design patterns for algorithms on trees.Tree Traversals →. On a binary search tree it visits elements in increasing order (tree with root 5, children 3 and 7, leaves 2, 4, 6, 8 gives 2, 3, 4, 5, 6, 7, 8).

Expressions. Fully parenthesized infix: a constant/variable, or (E1 Op E2)(E_1 \ \text{Op}\ E_2). Parse tree: proper binary tree, leaves = constants/variables, internal nodes = operators, left/right subtrees = parse trees of E1E_1, E2E_2; parentheses are implicit. With unary operators it is no longer proper. Postorder gives postfix (reverse Polish) notation: 15 x + 7 9 3 ÷ - * for ((15+x)∗(7−(9÷3)))((15 + x) * (7 - (9 \div 3))).

  • evaluateExpression (postorder): if internal, x <- eval(left), y <- eval(right), return x op y with op = v.getElement(); else return the element. Θ(n)\Theta(n), nn = constants + variables + operators. Example value 64 (with x=1x = 1).
  • infix (inorder): leaf: print the element; else print '(' + infix(left) + element + infix(right) + ')'. Θ(n)\Theta(n).

heightSum (sum of the heights of all nodes of a proper binary tree), postorder returning a pair (heightsum, height):

if T.isExternal(v) then return (0, 0)
(sL, hL) <- heightSum(T, T.left(v));  (sR, hR) <- heightSum(T, T.right(v))
h <- max{hL, hR} + 1;  s <- sL + sR + h;  return (s, h)

Θ(n)\Theta(n). Without returning the height, recomputing it at each node would revisit the subtree. Lesson: compute richer information than requested.

Typical mistakes: visiting the node at the wrong moment (evaluation needs postorder, infix generation needs inorder); forgetting the parentheses in infix; forgetting that the parse tree is proper only with binary operators.

See Binary TreesA binary tree is an ordered tree where each node has at most two children (left and right); in a proper binary tree every internal node has exactly two, which gives the leaf count m = n - m + 1 and bounds linking height, leaves and nodes.Binary Trees → and 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 →.

Teoria collegata