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:
- recursively visit the left subtree,
- then visit the parent,
- 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: , where is the number of nodes and the time of the visit of . 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, 8Arithmetic expressions
A binary operator acts on two operands: , , , . In the operator combines the operands 3 and 5.
In infix notation each binary operator is written between its two operands: , , .
A fully parenthesized expression in infix notation is:
- a constant or variable , or
- , where are fully parenthesized expressions in infix notation and Op is a binary operator.
Parentheses make the evaluation order explicit, independently of operator precedence. Example: .
Parse tree
The parse tree of an arithmetic expression (binary operators only) is a proper binary tree whose leaves contain the constants or variables of and whose internal nodes contain the operators of :
- if (constant or variable), is a single leaf containing ;
- if , the root of contains Op, and its left (right) subtree is the parse tree of ().
Parse tree of :
*
/ \
+ -
/ \ / \
15 x 7 ÷
/ \
9 3The 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. ) 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 (take the operator, apply it to the children's values). Initial call: evaluateExpression(T, T.root()).
Example above: with , (the value given in the slides).
Complexity with = root: , where is the number of nodes of , i.e. the number of constants, variables and operators of . It is the postorder analysis: the visit takes , 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 = root: , = number of constants, variables and operators of . Same analysis as inorder, with constant-cost visits.
Exercise: heightSum
The heightsum of a proper binary tree 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 , and analyse heightSum(T, T.root()) in terms of .
Naive idea. At an internal node with children : Problem: if the height of is not obtained recursively, computing it requires visiting all the nodes of again.
Idea. Postorder pattern, returning not only the sum of the heights in but also the height of itself. Otherwise, after the recursive calls on the children, the height of (and so the heightsum of ) 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 (heightsum 0, height 0). Postorder: recursive calls on the left and right subtrees first, then the visit of computes its height h and its heightsum s. Initial call: heightSum(T, T.root()).
Complexity: . Same analysis as postorder, with 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 , 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 . Parse tree: proper binary tree, leaves = constants/variables, internal nodes = operators, left/right subtrees = parse trees of , ; parentheses are implicit. With unary operators it is no longer proper. Postorder gives postfix (reverse Polish) notation: 15 x + 7 9 3 ÷ - * for .
- evaluateExpression (postorder): if internal,
x <- eval(left),y <- eval(right), returnx op ywithop = v.getElement(); else return the element. , = constants + variables + operators. Example value 64 (with ). - infix (inorder): leaf: print the element; else print
'(' + infix(left) + element + infix(right) + ')'. .
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). 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 →.