Complete the code to start a recursive tree traversal from the root node.
def traverse(node): if node is None: return print(node.value) traverse([1])
The recursive call should continue with the left child of the current node to traverse the tree.
Complete the code to count the total number of nodes in a binary tree recursively.
def count_nodes(node): if node is None: return 0 return 1 + count_nodes([1]) + count_nodes(node.right)
To count all nodes, recursively count nodes in the left subtree and right subtree. Here, the left subtree is accessed via node.left.
Fix the error in the recursive function to find the height of a binary tree.
def height(node): if node is None: return 0 left_height = height(node.left) right_height = height([1]) return 1 + max(left_height, right_height)
The height function must check both left and right children. The right child is accessed by node.right.
Fill both blanks to create a dictionary comprehension that maps each node's value to its depth in the tree.
def map_depths(node, depth=0): if node is None: return {} depths = {node.value: depth} depths.update(map_depths([1], depth + 1)) depths.update(map_depths([2], depth + 1)) return depths
To map depths correctly, recursively call the function on both left and right children, which are node.left and node.right.
Fill all three blanks to create a dictionary comprehension that maps each node's value in uppercase to its depth if depth is greater than 0.
def map_upper_depths(node, depth=0): if node is None: return {} depths = { [1]: [2] for k, v in map_upper_depths(node.left, depth + 1).items() if v [3] 0 } depths[node.value.upper()] = depth return depths
The comprehension maps keys to uppercase (k.upper()), values as v, and filters for depths greater than 0 (v > 0).