Forgetting null/base-case handling
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.
Move from brute-force thinking to an efficient approach using tree strategy.
There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of n cities numbered from 0 to n - 1 and exactly n - 1 roads. The capital city is city 0. You are given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi.
There is a meeting for the representatives of each city. The meeting is in the capital city.
There is a car in each city. You are given an integer seats that indicates the number of seats in each car.
A representative can use the car in their city to travel or change the car and ride with another representative. The cost of traveling between two cities is one liter of fuel.
Return the minimum number of liters of fuel to reach the capital city.
Example 1:
Input: roads = [[0,1],[0,2],[0,3]], seats = 5 Output: 3 Explanation: - Representative1 goes directly to the capital with 1 liter of fuel. - Representative2 goes directly to the capital with 1 liter of fuel. - Representative3 goes directly to the capital with 1 liter of fuel. It costs 3 liters of fuel at minimum. It can be proven that 3 is the minimum number of liters of fuel needed.
Example 2:
Input: roads = [[3,1],[3,2],[1,0],[0,4],[0,5],[4,6]], seats = 2 Output: 7 Explanation: - Representative2 goes directly to city 3 with 1 liter of fuel. - Representative2 and representative3 go together to city 1 with 1 liter of fuel. - Representative2 and representative3 go together to the capital with 1 liter of fuel. - Representative1 goes directly to the capital with 1 liter of fuel. - Representative5 goes directly to the capital with 1 liter of fuel. - Representative6 goes directly to city 4 with 1 liter of fuel. - Representative4 and representative6 go together to the capital with 1 liter of fuel. It costs 7 liters of fuel at minimum. It can be proven that 7 is the minimum number of liters of fuel needed.
Example 3:
Input: roads = [], seats = 1 Output: 0 Explanation: No representatives need to travel to the capital city.
Constraints:
1 <= n <= 105roads.length == n - 1roads[i].length == 20 <= ai, bi < nai != biroads represents a valid tree.1 <= seats <= 105Problem summary: There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of n cities numbered from 0 to n - 1 and exactly n - 1 roads. The capital city is city 0. You are given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi. There is a meeting for the representatives of each city. The meeting is in the capital city. There is a car in each city. You are given an integer seats that indicates the number of seats in each car. A representative can use the car in their city to travel or change the car and ride with another representative. The cost of traveling between two cities is one liter of fuel. Return the minimum number of liters of fuel to reach the capital city.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Tree
[[0,1],[0,2],[0,3]] 5
[[3,1],[3,2],[1,0],[0,4],[0,5],[4,6]] 2
[] 1
binary-tree-postorder-traversal)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2477: Minimum Fuel Cost to Report to the Capital
class Solution {
private List<Integer>[] g;
private int seats;
private long ans;
public long minimumFuelCost(int[][] roads, int seats) {
int n = roads.length + 1;
g = new List[n];
Arrays.setAll(g, k -> new ArrayList<>());
this.seats = seats;
for (var e : roads) {
int a = e[0], b = e[1];
g[a].add(b);
g[b].add(a);
}
dfs(0, -1);
return ans;
}
private int dfs(int a, int fa) {
int sz = 1;
for (int b : g[a]) {
if (b != fa) {
int t = dfs(b, a);
ans += (t + seats - 1) / seats;
sz += t;
}
}
return sz;
}
}
// Accepted solution for LeetCode #2477: Minimum Fuel Cost to Report to the Capital
func minimumFuelCost(roads [][]int, seats int) (ans int64) {
n := len(roads) + 1
g := make([][]int, n)
for _, e := range roads {
a, b := e[0], e[1]
g[a] = append(g[a], b)
g[b] = append(g[b], a)
}
var dfs func(int, int) int
dfs = func(a, fa int) int {
sz := 1
for _, b := range g[a] {
if b != fa {
t := dfs(b, a)
ans += int64((t + seats - 1) / seats)
sz += t
}
}
return sz
}
dfs(0, -1)
return
}
# Accepted solution for LeetCode #2477: Minimum Fuel Cost to Report to the Capital
class Solution:
def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int:
def dfs(a: int, fa: int) -> int:
nonlocal ans
sz = 1
for b in g[a]:
if b != fa:
t = dfs(b, a)
ans += ceil(t / seats)
sz += t
return sz
g = defaultdict(list)
for a, b in roads:
g[a].append(b)
g[b].append(a)
ans = 0
dfs(0, -1)
return ans
// Accepted solution for LeetCode #2477: Minimum Fuel Cost to Report to the Capital
impl Solution {
pub fn minimum_fuel_cost(roads: Vec<Vec<i32>>, seats: i32) -> i64 {
let n = roads.len() + 1;
let mut g: Vec<Vec<usize>> = vec![vec![]; n];
for road in roads.iter() {
let a = road[0] as usize;
let b = road[1] as usize;
g[a].push(b);
g[b].push(a);
}
let mut ans = 0;
fn dfs(a: usize, fa: i32, g: &Vec<Vec<usize>>, ans: &mut i64, seats: i32) -> i32 {
let mut sz = 1;
for &b in g[a].iter() {
if (b as i32) != fa {
let t = dfs(b, a as i32, g, ans, seats);
*ans += ((t + seats - 1) / seats) as i64;
sz += t;
}
}
sz
}
dfs(0, -1, &g, &mut ans, seats);
ans
}
}
// Accepted solution for LeetCode #2477: Minimum Fuel Cost to Report to the Capital
function minimumFuelCost(roads: number[][], seats: number): number {
const n = roads.length + 1;
const g: number[][] = Array.from({ length: n }, () => []);
for (const [a, b] of roads) {
g[a].push(b);
g[b].push(a);
}
let ans = 0;
const dfs = (a: number, fa: number): number => {
let sz = 1;
for (const b of g[a]) {
if (b !== fa) {
const t = dfs(b, a);
ans += Math.ceil(t / seats);
sz += t;
}
}
return sz;
};
dfs(0, -1);
return ans;
}
Use this to step through a reusable interview workflow for this problem.
BFS with a queue visits every node exactly once — O(n) time. The queue may hold an entire level of the tree, which for a complete binary tree is up to n/2 nodes = O(n) space. This is optimal in time but costly in space for wide trees.
Every node is visited exactly once, giving O(n) time. Space depends on tree shape: O(h) for recursive DFS (stack depth = height h), or O(w) for BFS (queue width = widest level). For balanced trees h = log n; for skewed trees h = n.
Review these before coding to avoid predictable interview regressions.
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.