Which statement best 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 have cycles and may not be connected.
Consider a graph and a tree each with 5 nodes. Which output correctly shows the number of edges in a tree with 5 nodes?
package main import "fmt" func main() { nodes := 5 // For a tree, edges = nodes - 1 edges := nodes - 1 fmt.Println(edges) }
Remember the formula for edges in a tree.
A tree with n nodes always has n-1 edges.
Which option correctly detects a cycle in an undirected graph represented by adjacency list?
func hasCycle(graph map[int][]int) bool { visited := make(map[int]bool) var dfs func(node, parent int) bool dfs = func(node, parent int) bool { visited[node] = true for _, neighbor := range graph[node] { if !visited[neighbor] { if dfs(neighbor, node) { return true } } else if neighbor != parent { return true } } return false } for node := range graph { if !visited[node] { if dfs(node, -1) { return true } } } return false }
Check how visited nodes and parent nodes are handled in DFS.
This code uses DFS and tracks parent nodes to detect cycles in undirected graphs correctly.
Given a tree and a graph with the same nodes, which traversal output is valid only for the tree?
Tree edges: 1-2, 1-3, 2-4, 2-5
Graph edges: same as tree plus an extra edge 3-5
Traversal starting at node 1 using DFS.
treeEdges := map[int][]int{ 1: {2, 3}, 2: {4, 5}, 3: {}, 4: {}, 5: {}, } graphEdges := map[int][]int{ 1: {2, 3}, 2: {4, 5}, 3: {5}, 4: {}, 5: {}, } // DFS traversal function omitted for brevity
Consider that the tree has no cycles and the graph has an extra edge.
DFS on the tree visits nodes in order [1, 2, 4, 5, 3]. The extra edge in the graph can change traversal order.
Which property makes trees a special type of graph?
Think about connectivity, cycles, and edges count.
Trees are connected graphs with no cycles and have exactly one less edge than nodes.
