ITPEC FE Subject B April 2024 Question 9
From the answer group below, select the correct combination of answers to be inserted into A through C in the program. Here, the array index starts at 1.
The procedure preorder traverses a binary tree and outputs the value of each node by following the sequence: root, left subtree, and right subtree using a stack (Last In, First Out). Each node of the binary tree is represented by the class Node. The table shows the description of the class Node. The Node-type variable holds a reference to an instance of the class Node. The argument root holds a reference to the root of the binary tree, which is an instance of the class Node. In the program, areas outside of the array must not be referenced.
Table Class Node
Answer group
Explanation
A: 0, B: v.right, C: v.left — the stack is empty when sp falls to 0, and the left child is pushed last so that it is popped first.
- •
spindexes the top element and starts at 1 with the root. Each pop lowers it, sosp = 0means the stack is empty: the loop runs whilespis not 0. - •Preorder visits the left subtree before the right one. A stack returns the last item pushed first, so the right child goes in first and the left child on top of it: B is
v., C isright v..left
Trace for root R with children L and S, where L has children X and Y:
The output is R, L, X, Y, S: root, then the whole left subtree, then the right subtree.
Answer (b)
Why not others:
- •(a) — pushing the left child first leaves the right child on top, so the right subtree is visited first: R, S, L, Y, X
- •(c) and (d) — A
-1keeps the loop running once the stack is empty (sp= 0), so it readsstack[0], outside the array
Key rule: A stack reverses the order of what goes in, so push the children in the reverse of the order you want to visit them; with 1-based indexing an empty stack has a pointer of 0.
Binary Search Tree · AI-written, may contain errors
This question comes from an official ITPEC past paper. ITPEC Practice is an independent study tool and is not affiliated with ITPEC. See the official FE past-paper collection or Report an issue.