📖 Scenario: Imagine you are organizing a family reunion and a city map. The family reunion represents a tree structure where each person has one parent except the root ancestor. The city map represents a graph where places are connected in many ways, possibly with loops.
🎯 Goal: You will create simple representations of a tree and a graph using adjacency lists in Go. Then, you will identify the key structural difference by checking if the graph contains cycles or not.
📋 What You'll Learn
Create a tree as an adjacency list with exact nodes and edges
Create a graph as an adjacency list with exact nodes and edges
Add a boolean variable called hasCycle to represent if the graph has cycles
Write a simple function to check for cycles in the graph
Print the adjacency lists and the cycle check result
💡 Why This Matters
🌍 Real World
Trees are used to represent hierarchical data like family trees or file systems, while graphs model complex networks like city maps or social connections.
💼 Career
Understanding the difference between trees and graphs and detecting cycles is fundamental for software engineers working on data modeling, network analysis, and algorithm design.
Progress0 / 4 steps
1
Create Tree and Graph Adjacency Lists
Create a variable called tree as a map[string][]string with these exact entries: "A": {"B", "C"}, "B": {"D", "E"}, "C": {}, "D": {}, "E": {}. Then create a variable called graph as a map[string][]string with these exact entries: "A": {"B", "C"}, "B": {"A", "D"}, "C": {"A", "E"}, "D": {"B", "E"}, "E": {"C", "D"}.
DSA Go
Hint
Use Go map with string keys and slice of strings as values to represent adjacency lists.
2
Add Cycle Detection Variable
Add a boolean variable called hasCycle and set it to false initially.
DSA Go
Hint
Just create a boolean variable named hasCycle and set it to false.
3
Implement Simple Cycle Check Function
Write a function called detectCycle that takes graph map[string][]string and returns a bool. Use a depth-first search approach with a helper function to detect if there is any cycle in the graph. Then call detectCycle(graph) and assign the result to hasCycle.
DSA Go
Hint
Use depth-first search with recursion and track nodes in the recursion stack to detect cycles.
4
Print Adjacency Lists and Cycle Result
Print the tree adjacency list, the graph adjacency list, and the value of hasCycle using fmt.Println.
DSA Go
Hint
Use fmt.Println to print the maps and the boolean variable.
Practice
(1/5)
1. Which of the following is a key structural difference between a tree and a graph?
easy
A. A tree has no cycles, but a graph can have cycles.
B. A graph always has a root node, but a tree does not.
C. A tree can have multiple edges between the same nodes, but a graph cannot.
D. A graph is always directed, but a tree is always undirected.
Solution
Step 1: Understand the cycle property of trees and graphs
A tree is a special type of graph that does not contain any cycles, meaning you cannot start at one node and return to it by following edges. Graphs, however, can have cycles.
Step 2: Analyze the options based on this property
A tree has no cycles, but a graph can have cycles. correctly states that trees have no cycles while graphs can have cycles. Other options incorrectly describe properties of trees and graphs.
Final Answer:
A tree has no cycles, but a graph can have cycles. -> Option A
Quick Check:
Cycle presence = Tree no, Graph yes [OK]
Hint: Trees never loop back; graphs can have loops [OK]
Common Mistakes:
Thinking graphs always have a root node
Believing trees can have cycles
Confusing directed and undirected properties
2. Which of the following Go code snippets correctly declares an adjacency list for an undirected tree with 3 nodes?
easy
A. adj := map[int]int{1: 2, 2: 3, 3: 1}
B. adj := [][]int{{1, 2}, {2, 3}, {3, 1}}
C. adj := map[int][]int{1: {2}, 2: {1, 3}, 3: {2}}
D. adj := map[int][]int{1: {2, 3}, 2: {3}, 3: {1}}
Solution
Step 1: Understand adjacency list representation in Go
An adjacency list for a graph or tree is usually a map from node to a slice of connected nodes. For an undirected tree, edges are bidirectional.
Step 2: Check each option for correctness
adj := map[int][]int{1: {2}, 2: {1, 3}, 3: {2}} correctly shows node 1 connected to 2, node 2 connected to 1 and 3, and node 3 connected to 2, representing an undirected tree. Options A and C use incorrect types or structures. adj := map[int][]int{1: {2, 3}, 2: {3}, 3: {1}} incorrectly connects nodes, creating extra edges.
Hint: Skip parent node when checking visited neighbors [OK]
Common Mistakes:
Not ignoring parent node in DFS
Assuming visited means cycle without context
Starting DFS from wrong node
5. You have a graph represented by an adjacency list in Go. You want to verify if it is a tree. Which combination of checks correctly confirms this?
A tree must be connected and have no cycles. Which code snippet below correctly implements this logic?
func isTree(graph map[int][]int) bool {
visited := make(map[int]bool)
var dfs func(int, int) bool
dfs = func(node, parent int) bool {
visited[node] = true
for _, neighbor := range graph[node] {
if !visited[neighbor] {
if !dfs(neighbor, node) {
return false
}
} else if neighbor != parent {
return false
}
}
return true
}
if !dfs(1, -1) {
return false
}
for node := range graph {
if !visited[node] {
return false
}
}
return true
}
hard
A. The code incorrectly assumes node 0 as root.
B. The code correctly checks for cycles and connectivity to confirm a tree.
C. The code only checks cycles but not connectivity.
D. The code only checks connectivity but not cycles.
Solution
Step 1: Check cycle detection in DFS
The DFS function returns false if it finds a back edge (visited neighbor not parent), correctly detecting cycles.
Step 2: Check connectivity after DFS
After DFS from node 1, the code checks if all nodes were visited, ensuring the graph is connected.
Step 3: Confirm both conditions for tree
Since the code checks both no cycles and connectivity, it correctly confirms if the graph is a tree.
Final Answer:
The code correctly checks for cycles and connectivity to confirm a tree. -> Option B
Quick Check:
Cycle check + connectivity = tree confirmation [OK]
Hint: Check no cycles and all nodes visited for tree [OK]
Common Mistakes:
Checking only cycles or only connectivity
Not verifying all nodes are visited
Assuming any connected graph is a tree
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.