Embercode
✕
Binary TreesQuick quiz

Tree bug hunt

8 questions. Covers Debugging lab: tree recursion bugs in Python.

Questions 1 to 5 of 8

  1. 1. This function should count the nodes in a tree. Called on the tiny tree (a root 1 with one left child 2), it raises AttributeError. Which change fixes it? ``python def count_nodes(node): if node.left is None and node.right is None: return 1 return 1 + count_nodes(node.left) + count_nodes(node.right) ``
  2. 2. This function should return the height of a tree in edges. The sample tree has root 1, children 2 and 3, and grandchildren 4, 5 and 6, so its height is 2. Calling the function on the sample tree returns 0. What is the cause? ``python def height(node): if node is None: return 0 return max(height(node.left), height(node.right)) ``
  3. 3. This function should return True when the value is anywhere in the tree. Called with 6 on the sample tree, it returns False, even though 6 is under node 3. ``python def contains(node, target): if node is None: return False if node.value == target: return True return contains(node.left, target) and contains(node.right, target) `` Which change makes it correct for every value?
  4. 4. This function should swap the left and right children of every node. Calling it on the sample tree raises RecursionError. Why? ``python def mirror(node): if node is None: return temp = node.left node.left = node.right node.right = temp mirror(node) ``
  5. 5. This code counts the leaves with a shared counter. The variable s is the sample tree. What does it print? ``python leaf_count = 0 def count_leaves(node): global leaf_count if node is None: return 0 if node.left is None and node.right is None: leaf_count += 1 count_leaves(node.left) count_leaves(node.right) return leaf_count print('first call = ' + str(count_leaves(s))) print('second call = ' + str(count_leaves(s))) ``

5 question(s) left on this page.