Which statement correctly describes the key structural difference between a graph and a tree?
Think about connectivity and cycles in both structures.
A tree is a special type of graph that is connected and has no cycles. Graphs can be disconnected and may contain cycles.
What is the output of the following Python code that checks edge counts for a graph and a tree?
def is_tree(num_nodes, edges): return len(edges) == num_nodes - 1 # Graph with 4 nodes and 4 edges graph_edges = [(1,2), (2,3), (3,4), (4,1)] # Tree with 4 nodes and 3 edges tree_edges = [(1,2), (2,3), (3,4)] print(is_tree(4, graph_edges)) print(is_tree(4, tree_edges))
Recall the edge count property of trees.
A tree with n nodes must have exactly n-1 edges. The graph has 4 edges, so it is not a tree.
What error does the following code produce when checking if a graph is a tree by detecting cycles?
def has_cycle(graph, node, visited, parent): visited.add(node) for neighbor in graph[node]: if neighbor not in visited: if has_cycle(graph, neighbor, visited, node): return True elif neighbor != parent: return True return False graph = {1: [2], 2: [1, 3], 3: [2, 4]} visited = set() print(has_cycle(graph, 1, visited, -1))
Check if all keys exist in the graph dictionary.
The graph dictionary does not have a key for node 3's neighbor 4, causing a KeyError when accessing graph[4].
What is the output of the BFS traversal starting from node 1 on the following graph and tree?
from collections import deque def bfs(graph, start): visited = set() queue = deque([start]) order = [] while queue: node = queue.popleft() if node not in visited: visited.add(node) order.append(node) queue.extend(graph[node]) return order graph = {1: [2, 3], 2: [1, 4], 3: [1], 4: [2, 1]} tree = {1: [2, 3], 2: [4], 3: [], 4: []} print(bfs(graph, 1)) print(bfs(tree, 1))
Consider how BFS visits nodes level by level.
BFS visits nodes in order of their distance from the start. Both structures produce the same BFS order here.
Why is it impossible for a tree to have cycles, but graphs can have cycles?
Think about the formal definition of a tree.
Trees are a special type of graph that must be connected and have no cycles by definition. Graphs do not have this restriction and can contain cycles.
