A-level Computing COMP3 Tree Traversals COMP3: Section 3.3.2 Programming Concepts: Standard Algorithms Graphs and trees In this topic you will cover: • rooted trees • multiway trees • binary trees • in-order, pre-order and post-order tree traversals of a binary tree. Rooted trees A rooted tree is an abstract data type consisting of nodes arranged in hierarchical fashion, except when the tree is empty, linked by branches with a single node called the root at the top of the tree and every other node a descendent of the root. All nodes below the root have one and only one parent node as shown in Figure 1. A node that has a parent and itself is a parent of one or more nodes is known as an internal node. A node that has a parent node but is not a parent of other nodes is known as a leaf or terminal node. Figure 1 An example of a multiway tree The root node An internal node A leaf node A node A branch See also Section 2.5 of the Nelson Thornes book, AQA Computing A2, by Kevin Bond & Sylvia Langfield for more information. Choose option A-level Computing – COMP3 – Tree traversals Binary Trees A binary tree is a tree in which each node is the parent of at most two other nodes is known as a binary tree as shown in Figure 2. In a binary tree, there are never more than two branches descending from a node. Figure 2 An example of a binary tree The root node AQA Education (AQA) is a registered charity (number 1073334) and a company limited by guarantee registered in England and Wales (number 3644723). Our registered address is AQA, Devas Street, Manchester M15 6EX. 2 of 20 A-level Computing – COMP3 – Tree traversals An alternative definition of a binary tree is as follows. A binary tree is an abstract data type defining a finite set of elements. The set is either empty or is partitioned into three subsets. The first subset contains a single element called the root of the tree. The other two subsets are themselves binary trees, called the left and right sub-trees of the original tree. This alternative view of a tree is shown in Figure 3. Figure 3 Root, left sub-tree and right sub-tree view of binary tree The root node Left sub-tree Right sub-tree AQA Education (AQA) is a registered charity (number 1073334) and a company limited by guarantee registered in England and Wales (number 3644723). Our registered address is AQA, Devas Street, Manchester M15 6EX. 3 of 20 A-level Computing – COMP3 – Tree traversals This view of the original binary tree can be applied to each sub-tree. For example the left sub-tree consists of a root and two sub-trees. In turn each of these new sub-trees can be defined in terms of their root, left and right sub-trees, et cetera. Eventually, the sub-trees so defined satisfy the empty case. Figure 4 illustrates this in a simpler example. Figure 4 Division of a binary tree into Root of left subtree a root, left sub-tree and right sub-tree Root Left sub-tree Left sub-sub-tree which happens to be empty Right sub-tree Right sub-sub-tree which happens to be empty AQA Education (AQA) is a registered charity (number 1073334) and a company limited by guarantee registered in England and Wales (number 3644723). Our registered address is AQA, Devas Street, Manchester M15 6EX. 4 of 20 A-level Computing – COMP3 – Tree traversals Why binary trees are useful Binary trees are useful because they can represent the order in which mathematical expressions are evaluated. For example, the mathematical expression (z + 6) * (y –3) is represented in a binary tree as follows: Figure 5 An evaluation tree * + z 6 y 3 The expression in the tree is evaluated from the bottom up and from left to right. Table 1 shows the order of evaluation. Table 1 z+6 y+3 intermediate result 1 * intermediate result 2 Evaluation order intermediate result 1 intermediate result 2 final result AQA Education (AQA) is a registered charity (number 1073334) and a company limited by guarantee registered in England and Wales (number 3644723). Our registered address is AQA, Devas Street, Manchester M15 6EX. 5 of 20 A-level Computing – COMP3 – Tree traversals Binary Tree as a Data Structure Processing a binary tree on paper is straightforward. We have just done so with the evaluation tree in Figure 5. Processing a binary tree by computer is not so straightforward when the programming language that is used does not have a binary tree data type. Compare this situation with processing integer values in Pascal. Pascal has a native data type called Integer and in-built operators that act on integer values and variables of the integer data type. On the other hand, Pascal does not have a native data type to represent a binary tree nor does it have any in-built operators for manipulating binary trees. Using Pascal for binary tree processing thus requires the programmer to build binary trees from what is available in the language. The building blocks that are used are called the primitives of the language. We shall use the array primitive and the record primitive to construct a data structure in Pascal that represents a binary tree. The binary tree in Figure 5 now becomes a data structure in which the nodes are records with the field structure: NodeType = Record LeftPointer : Integer; Item : String; RightPointer : Integer; End; A pointer is a kind of address. Figure 6 illustrates this. Each record is numbered (given an address). The record numbers range from 1 to 7. Zero is used to represent the null pointer, the pointer that points nowhere. Figure 6 Binary tree represented by a collection of records Item 1 LeftPointer 2 * RightPointer 3 2 4 + 3 5 4 0 z 6 5 0 0 6 - 7 6 1 0 y 7 0 0 3 AQA Education (AQA) is a registered charity (number 1073334) and a company limited by guarantee registered in England and Wales (number 3644723). Our registered address is AQA, Devas Street, Manchester M15 6EX. 0 6 of 20 A-level Computing – COMP3 – Tree traversals The records need to be stored in a one-dimensional array with the structure ArrayOfNodesType = Array[1..7] Of NodeType; A variable called Root node pointer stores a pointer to the root node row of the array. Figure 7 Root node pointer 1 Binary tree stored in an array of records 1 2 * 3 2 4 + 5 3 6 - 7 4 0 z 0 5 0 6 0 6 0 y 0 7 0 3 0 Array subscript Ordered Binary Tree It is possible using a binary tree to sort an unordered list of items into a particular order. For example, consider the following unordered list of integers: 30 20 41 25 37 17 56 An ordered binary tree is created as follows. Starting from the leftmost integer in the list, the root node is created first. 30 The next integer is taken and placed in the left sub-tree if it is numerically less than the root node integer (or equal) or in the right sub-tree if it is numerically greater. 30 20 AQA Education (AQA) is a registered charity (number 1073334) and a company limited by guarantee registered in England and Wales (number 3644723). Our registered address is AQA, Devas Street, Manchester M15 6EX. 7 of 20 A-level Computing – COMP3 – Tree traversals The next integer is numerically greater than the root node integer and so goes into the right subtree. 30 20 41 The next integer is numerically less than the root node integer but greater than the integer at the root of the left sub-tree so it is placed to the right of this node. 30 20 41 25 The remainder of the list is processed to produce the finished ordered binary tree shown in Figure 8. Figure 8 An ordered binary tree 30 20 17 41 25 37 56 By visiting the nodes of this tree in left to right, bottom to top order an ordered equivalent of the original list is produced. This ordered list has placed the integers in ascending numerical order as follows: 17 20 25 30 37 41 56 AQA Education (AQA) is a registered charity (number 1073334) and a company limited by guarantee registered in England and Wales (number 3644723). Our registered address is AQA, Devas Street, Manchester M15 6EX. 8 of 20 A-level Computing – COMP3 – Tree traversals Traversal of a binary tree Traversal of a binary tree means to visit each node of the tree in some order. Usually, the visit means do something with the node, e.g. print its data value. There are three principle ways of traversing a binary tree: 1. Pre-order traversal 2. In-order traversal 3. Post-order traversal These traversals can be specified recursively. The trick is to realise that a binary tree can be defined recursively. The recursive definition states: a tree is either empty or consists of 1. A root 2. A left sub-tree 3. A right- sub-tree. Algorithms Pre-order Traversal a. If tree empty do nothing Otherwise b. Visit the root (e.g. print the value of the data item at the root) c. Traverse the left sub-tree in pre-order d. Traverse the right sub-tree in pre-order In-order Traversal 1. If tree empty do nothing Otherwise 2. Traverse the left sub-tree in in-order 3. Visit the root 4. Traverse the right sub-tree in in-order Post-order Traversal 1. If tree empty do nothing Otherwise 2. Traverse the left sub-tree in post-order 3. Traverse the right sub-tree in post-order 4. Visit the root AQA Education (AQA) is a registered charity (number 1073334) and a company limited by guarantee registered in England and Wales (number 3644723). Our registered address is AQA, Devas Street, Manchester M15 6EX. 9 of 20 A-level Computing – COMP3 – Tree traversals Examples D a. pre-order DAE b. in-order ADE c. post-order AED A E D B A F C E G a. pre-order DBACFEG b. in-order ABCDEFG c. post-order ACBEGFD + * A / C E G a. pre-order +*AC/EG b. in-order A*C+E/G (order of evaluation is (A*C) + (E/G)) c. post-order AC*EG/+ (Reverse Polish form) Tracing a particular traversal of a binary tree There are two ways to help you trace a particular traversal of a binary tree. First method The first places labels on nodes to aid remembering how far the trace has reached. Figure 9 shows a partial trace for a pre-order traversal through the given tree. All three stages of the algorithm have been applied to the left sub-tree and the root. The right sub-tree is being traced currently. AQA Education (AQA) is a registered charity (number 1073334) and a company limited by guarantee registered in England and Wales (number 3644723). Our registered address is AQA, Devas Street, Manchester M15 6EX. 10 of 20 A-level Computing – COMP3 – Tree traversals Figure 9 Partial tracing of binary tree If tree empty do nothing Otherwise a. Visit the root (e.g. print the value of the data item at the root) b. Traverse the left sub-tree in pre-order c. Traverse the right sub-tree in pre-order ab D abc a A E Second method This involves drawing an outline around the tree for each traversal as follows: Pre-order traversal Starting to the left of the root, draw an outline around the tree as shown in Figure 10. As you pass to the left of a node (where the red dot is marked) output the data in that node, i.e. DBACFEG Figure 10 Pre-order traversal of a binary tree using an outline around the tree as a guide D B A F C E G AQA Education (AQA) is a registered charity (number 1073334) and a company limited by guarantee registered in England and Wales (number 3644723). Our registered address is AQA, Devas Street, Manchester M15 6EX. 11 of 20 A-level Computing – COMP3 – Tree traversals In-order traversal Starting to the left of the root, draw an outline around the tree as shown in Figure 11. As you pass underneath a node (where the blue dot is marked) output the data in that node, i.e. ABCDEFG Figure 11 In-order traversal of a binary tree using an outline around the tree as a guide D B A F C E G Post-order traversal Starting to the left of the root, draw an outline around the tree as shown in Figure 12. As you pass to the right of a node (where the green dot is marked) output the data in that node, i.e. ACBEGFD Figure 12 Post-order traversal of a binary tree using an outline around the tree as a guide D B A F C E G AQA Education (AQA) is a registered charity (number 1073334) and a company limited by guarantee registered in England and Wales (number 3644723). Our registered address is AQA, Devas Street, Manchester M15 6EX. 12 of 20 A-level Computing – COMP3 – Tree traversals End of sub-topic questions 1 What output is produced by each of the following tree traversals applied to the binary tree in Figure 13? (a) (b) (c) Pre-order In-order Post-order Figure 13 Binary tree + * / - A E + B C G D AQA Education (AQA) is a registered charity (number 1073334) and a company limited by guarantee registered in England and Wales (number 3644723). Our registered address is AQA, Devas Street, Manchester M15 6EX. 13 of 20 A-level Computing – COMP3 – Tree traversals 2 (a) An algebraic expression is represented in a binary tree as follows. * + A (i) B C D Using a copy of this tree, label its root, a branch and a leaf node. (3 marks) (ii) On the same copy, mark and label the left sub-tree and the right sub-tree of this tree. (2 marks) (b) A recursively-defined procedure T, which takes a tree structure, tree(x, y, z) as its single parameter, where x is the root, y is the left sub-tree and z is the right sub-tree, is defined below. (<> means not equal to) Procedure T ( tree(x, y, z) ) If y <> empty Then PRINT ‘(‘ T(y) EndIf PRINT x If z <> empty Then T( z ) PRINT ‘)’ EndIf EndProc What is meant by recursively-defined? (1 mark) (c) Explain why a stack is necessary in order to execute procedure T recursively. (3 marks) (d) Dry run the following procedure call T( tree( ‘*’, tree ( ‘+’, tree ( ‘A’, empty, empty ), tree ( ‘B’, empty, empty ) ), tree ( ‘-’, tree ( ‘C’, empty, empty ), tree ( ‘D’, empty, empty ) ) ) ) showing clearly the PRINTed output and the values of the parameter omitted table (rows 4, 5, 6, 7) for the seven calls of T. AQA Education (AQA) is a registered charity (number 1073334) and a company limited by guarantee registered in England and Wales (number 3644723). Our registered address is AQA, Devas Street, Manchester M15 6EX. from the 14 of 20 A-level Computing – COMP3 – Tree traversals Call Number Parameter 1 tree(‘*’, tree(‘+’, tree(‘A’,empty,empty), tree(‘B’,empty,empty) ), tree(‘-’, tree(‘C’,empty,empty), tree(‘D’,empty,empty) ) ) 2 tree(‘+’, tree(‘A’,empty,empty), tree(‘B’,empty,empty)) 3 tree(‘A’,empty,empty) 4 5 6 7 (10 marks) (e) What tree traversal algorithm does procedure T describe? 3 The algebraic expression (1 mark) A*B+C*D as is stored as a binary tree in the three arrays term, leftpointer and rightpointer, shown in the table. Term LeftPointer RightPointer (a) 1 + 2 3 2 * 4 5 Subscript 3 4 5 * A B 6 0 0 7 0 0 6 C 0 0 7 D 0 0 What is a binary tree? Draw a diagram of the binary tree represented by the three arrays term, rightpointer. leftpointer, (6 marks) (b) A recursively-defined procedure P, which takes an integer as its single parameter, is defined below. Procedure P (Subscript) If LeftPointer[Subscript] > 0 Then P (LeftPointer[Subscript]) EndIf If RightPointer[Subscript] > 0 Then P (RightPointer[Subscript]) EndIf Print Term[Subscript] End Of P AQA Education (AQA) is a registered charity (number 1073334) and a company limited by guarantee registered in England and Wales (number 3644723). Our registered address is AQA, Devas Street, Manchester M15 6EX. 15 of 20 A-level Computing – COMP3 – Tree traversals What is meant by recursively-defined? (c) (1 mark) Explain why a stack is necessary in order to execute procedure P recursively. (2 marks) (d) Using as an aid a copy of the partially completed table shown below, and given that the three arrays term, leftpointer and rightpointer are global, dry run the procedure call P (1) showing clearly the PRINTed output and the values of the parameter omitted from the table for the seven calls of P. ------------------------| Call | Parameter | | Number | | -------------------------| 1 | 1 | | 2 | 2 | | 3 | 4 | | 4 | 5 | | 5 | | | 6 | | | 7 | | ------------------------(10 marks) (e) What tree traversal algorithm does procedure P describe? (1 mark) AQA Education (AQA) is a registered charity (number 1073334) and a company limited by guarantee registered in England and Wales (number 3644723). Our registered address is AQA, Devas Street, Manchester M15 6EX. 16 of 20 A-level Computing – COMP3 – Tree traversals Solutions 1 (a) pre-order: +*-AB+CD/EG (b) in-order: (A-B)*(C+D)+(E/G) (c) post-order: AB-CD+*EG/+ (3 marks) 2 (a)(i) Root * - + A B Branch Labelling must clearly indicate term D C Leaf Node (3 marks) (a)(ii) Left Sub Tree Right Sub Tree * + A Must clearly indicate subsets B C D (2 marks) (b) A procedure which is defined in terms of/calls itself/re-entrant (1 mark) (c) State of machine/return address/parameter needs to be stored/held to enable a previous execution of T to be resumed Or so that each call to T can pass a new value of the parameter (3 marks) AQA Education (AQA) is a registered charity (number 1073334) and a company limited by guarantee registered in England and Wales (number 3644723). Our registered address is AQA, Devas Street, Manchester M15 6EX. 17 of 20 A-level Computing – COMP3 – Tree traversals (d) Call Number Parameter 1 tree(‘*’, tree(‘+’, tree(‘A’,empty,empty), tree(‘B’,empty,empty) ), tree(‘-’, tree(‘C’,empty,empty), tree(‘D’,empty,empty) ) ) 2 tree(‘+’, tree(‘A’,empty,empty), tree(‘B’,empty,empty)) 3 tree(‘A’,empty,empty) 4 tree(‘B’,empty,empty) 1 5 tree(‘-’,tree(‘C’,empty,empty),tree(‘D’,empty,empty) ) 1 6 tree(‘C’,empty,empty) 1 7 tree(‘D’,empty,empty) 1 1 1 1 ( ( A +B ) * ( C – D ) ) 1 1 Must be in middle for mark 1 (max 10 marks) (e) In-order traversal (1 mark) (Total: 20 marks) AQA Education (AQA) is a registered charity (number 1073334) and a company limited by guarantee registered in England and Wales (number 3644723). Our registered address is AQA, Devas Street, Manchester M15 6EX. 18 of 20 A-level Computing – COMP3 – Tree traversals 3 (a) 1 mark for stating what constitutes a binary tree: A tree in which each node is the parent of at most two other nodes is known as a binary tree. Or A finite set of elements which is either empty or is partitioned into three disjoint subsets. The first subset contains a single element called the root of the tree. The other two subsets are themselves binary trees, called the left and right subtrees of the original tree. Or A diagram showing more than two levels Or A labelled diagram showing just two levels and using terms root|root node, node|leaf|leaf node. (1 mark) -------N.B. accept nodes without operators but with subscripts which correctly reference these operators + * A (1 mark) (1 mark) (1 mark) B * (1 mark) C (1 mark) D (max 6 marks) (b) Procedure which is defined in terms of itself, i.e. contains within its body a reference to itself. Or A procedure which calls itself. (1 mark) (c)The current state of the machine/one of: return address, procedure parameter, status register, other register values, local variables - must be saved/preserved so can return correctly to previous invocation of P (1 mark) Or because P must be re-entrant (2 marks) AQA Education (AQA) is a registered charity (number 1073334) and a company limited by guarantee registered in England and Wales (number 3644723). Our registered address is AQA, Devas Street, Manchester M15 6EX. 19 of 20 A-level Computing – COMP3 – Tree traversals (d) N.B. Accept printed output in form AB*CD*+ Or A B * C D * + ...1 ...1 ...1 ...1 ...1 ...1 ...1 For those candidates who make a mistake the following guide should be followed: marks are for A first(1), if A not first AB (1)|AB*(2) B in wrong place B*(1) in any position CD(2)|CD*(3) in wrong position D*(1)|D*+(2) e.g. CD*AB*+ gets a mark of 6 (max 7 marks) Parameter values @ 1 mark each up to max 3 marks Call No 1 2 3 4 5 6 7 Parameter Printed Output 1 + 2 * 4 A 5 B 3 ..1 mark * 6 ..1 mark C 7 ..1 mark D (e) Post-order/converts infix to postfix (1 mark) (Total 17 marks) In this topic you have covered: • a rooted multiway tree • a binary tree • why binary trees are useful • binary tree as a data structure • constructing an ordered binary tree • tree traversals - pre-order, in-order, post-order • tracing tree traversals. Reproduced by permission of Dr K Bond. All rights reserved. AQA Education (AQA) is a registered charity (number 1073334) and a company limited by guarantee registered in England and Wales (number 3644723). Our registered address is AQA, Devas Street, Manchester M15 6EX. 20 of 20
© Copyright 2025 Paperzz