Consider a binary tree where each node has a value and two children (left and right). Which of the following best describes the order of nodes visited in a preorder traversal?
Preorder means you visit the root before its children.
In preorder traversal, the root node is visited first, then the left subtree is traversed recursively, followed by the right subtree.
What is the typical base case condition in a recursive function that processes nodes of a binary tree?
Think about when there is no node to process.
The base case for recursive tree functions is usually when the node is null, meaning there is no node to process, so recursion stops.
Given a binary tree, which recursive approach correctly calculates its height (the number of edges on the longest path from root to a leaf)?
def tree_height(node): if node is None: return -1 left_height = tree_height(node.left) right_height = tree_height(node.right) return 1 + max(left_height, right_height)
Height of an empty tree is usually defined as -1 or 0 depending on convention.
For height as number of edges, empty tree height is -1. Returns -1 for null nodes and adds 1 plus the maximum height of left and right subtrees correctly computes it.
What is the time complexity of a recursive depth-first search (DFS) on a binary tree with n nodes?
Consider how many nodes the algorithm visits in the worst case.
DFS visits every node once, so the time complexity is linear in the number of nodes, O(n).
Consider two binary trees each with 15 nodes: one is perfectly balanced, and the other is skewed (all nodes have only one child). How does the maximum recursion depth during a full traversal compare between these two trees?
Think about how tree height affects recursion depth.
The balanced tree has height about log2(15) ≈ 4, so recursion depth is about 4. The skewed tree is like a linked list with height 15, so recursion depth is 15.