- A binary tree Node sets
self.left = None in __init__. After n = Node(5), what happens when print(n.left.val) runs? Answer: AttributeError
n.left is None, and None has no val attribute, so Python raises AttributeError. It does not print None. You must check if n.left is not None before following a child link.
- A tree is stored as
t = {"A": ["B", "C"], "B": []}. What happens when print(len(t["C"])) runs? Answer: KeyError
Leaf "C" appears only inside A's child list. It was never added as a key, so t["C"] raises KeyError. Printing 0 would need an entry like "C": [] in the dict.
- What does this print?
t = {"A": ["B", "C"], "B": ["D"], "C": [], "D": []}; print([k for k in t if not t[k]]) Answer: ['C', 'D']
not t[k] is True when the child list is empty, so the comprehension collects the leaves C and D. The answer ['A', 'B'] would come from dropping not, which keeps the nodes that do have children.
- A tree with n nodes is stored as a dict mapping each node to a list of its children only. How many child entries appear in all lists combined?
Answer: n - 1
Every node except the root has exactly one parent, so it appears in exactly one child list: n - 1 entries. The value 2 * (n - 1) would apply only if each edge were stored in both directions.
root is a Node with a val attribute and a children list of Node objects. Which expression gives the value of root's first child? Answer: root.children[0].val
root.children is a list, [0] picks its first Node, and .val reads that Node's value. root.children.val[0] fails because a list has no val attribute.