Trees and graphs · A level · OCR H446 1.4.2, AQA 7517 4.2.5.1, Eduqas A500QS 1.1 · about 25 min
Trees as connected graphs with no cycles, rooted trees and their vocabulary, binary trees and typical uses.
[1 mark]Which is the definition of a tree?
[1 mark]A tree has 20 vertices. How many edges does it have?
[1 mark]In a rooted tree, which node has no parent?
[1 mark]Which of these are typical uses of rooted trees?
Tick every answer that is true.
[1 mark]What is a binary tree?
[1 mark]What does this program print?
CHILDREN = {"r": ["a", "b"], "a": ["c", "d", "e"], "b": ["f"]}
def leaves(node):
kids = CHILDREN.get(node, [])
if not kids:
return 1
return sum(leaves(k) for k in kids)
print(leaves("r"), leaves("a"))
TREE is a rooted tree stored as a dictionary: each key is a node that has children, and its value is the list of those children. Leaves appear only inside children lists, never as keys, and the keys are in no particular order, so the root is not necessarily first. Write a recursive function height(node) that returns the height of the subtree rooted at node, which is 0 for a leaf. Then print five lines: root: and the root; nodes: and the number of nodes; edges: and the number of edges; leaves: and every leaf in alphabetical order, separated by single spaces; and height: and the height of the whole tree. Work everything out from TREE.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
TREE = {
"fetch": ["approach", "grip"],
"mission": ["find", "fetch", "return"],
"approach": ["align", "creep"],
"find": ["scan", "turn"],
"return": ["drive", "drop"],
}
def height(node):
return 0Plan your program here, then type it in and press Run.
TREE with its depth, the root first.TREE so that its height becomes 4, and check your program agrees.is_binary(tree) that returns True when no node in a tree stored like TREE has more than two children.