Check your understanding of the previous reading: tree vocabulary, the parts of a recursive function, recursion and loops, and the types of the expressions in a recursive function.

Question 1

Match each term to the best definition.

#DefinitionTerm
1 The top node in a tree, without any parents.
2 A bottom node in a tree, without any children.
3 A given element in a tree.
4 The connection between elements in a tree.
5 A data structure holding elements with parent and child relationships.
6 A node that has one or more nodes under it.
7 A node that is subordinate to another node.

Question 2

Match each term from the reading to the best explanation.

#ExplanationTerm
1 When the function being defined is used in its own definition.
2 A logical decision in the code to do different things based on a condition.
3 To bring together the results of the recursive calls and the current element.
4 The process of reducing down the original argument before the recursive call.
5 The simpler branch of a recursive function, where the recursion terminates with a simple value.
6 The other branch of a recursive function, where the recursive call and combination happens.

Question 3

Anything you can do with recursion, you can do with a while loop (and vice versa), since they are both looping constructs.

Select one answer, then check.

  • Correct: recursion and while loops are equally powerful. Recursion is another approach to looping: a while loop that keeps a list of the work still to do can do anything a recursive function does, and a recursive function can replace any while loop, although for a given problem one of the two is often much simpler.
  • Not quite: recursion and while loops are equally powerful. Recursion is another approach to looping: a while loop that keeps a list of the work still to do can do anything a recursive function does, and a recursive function can replace any while loop, although for a given problem one of the two is often much simpler.

Question 4

Given the following code, determine the most accurate type for each expression on its line.

from dataclasses import dataclass

@dataclass
class Tree:
    pass

@dataclass
class BinaryTree(Tree):
    value: int
    left: Tree
    right: Tree

EMPTY = Tree()

def sum_tree(tree: Tree) -> int:
    if tree == EMPTY:
        return 0
    left_side = sum_tree(tree.left)
    right_side = sum_tree(tree.right)
    result = tree.value + left_side + right_side
    return result
#ExpressionType
1 tree in the branch's condition
2 tree inside the base case
3 tree inside the recursive case
4 tree.left inside the recursive case
5 left_side
6 tree.value inside the recursive case
7 result