Practice
Solution
Step 1: Trace dfs on leaf nodes 1 and 2
Leaves return NOT_COVERED (0) because their children are null and return COVERED_NO_CAM (1). So dfs(1) and dfs(2) return NOT_COVERED.Step 2: At root node 0, left or right child is NOT_COVERED, so place a camera here
Increment cameras to 1 and return HAS_CAM (2). The root is covered, so no extra camera needed.Final Answer:
Option D -> Option DQuick Check:
One camera at root covers all nodes [OK]
- Counting cameras on leaves instead of parent
- Forgetting to add camera at root if uncovered
- Misinterpreting coverage states
Solution
Step 1: Understand traversal order requirement
The problem requires visiting root before left and right subtrees, which is preorder traversal.Step 2: Identify approach with no extra space
Morris preorder traversal uses threaded binary trees to achieve preorder traversal without recursion or stack, thus optimal in space.Final Answer:
Option C -> Option CQuick Check:
Preorder visits root first; Morris traversal achieves this with O(1) space [OK]
- Confusing inorder or postorder with preorder traversal
- Assuming recursion is always needed
- Using level-order which visits nodes by depth
Solution
Step 1: Identify DFS traversal cost
The algorithm visits each node exactly once in a postorder DFS traversal.Step 2: Analyze operations per node
At each node, constant time operations are done: combining left and right child results, no repeated work.Final Answer:
Option C -> Option CQuick Check:
Linear traversal of n nodes -> O(n) time [OK]
- Assuming O(n^2) due to grandchildren checks
- Confusing recursion stack space with time complexity
Solution
Step 1: Understand the impact of allowing node reuse
Allowing cycles means paths can revisit nodes infinitely, so naive DFS or postorder traversal fails due to infinite loops.Step 2: Identify correct approach
Dynamic programming with cycle detection and memoization prevents infinite recursion and correctly computes max sums with repeated nodes.Final Answer:
Option B -> Option BQuick Check:
Memoization with cycle detection handles repeated nodes safely [OK]
- Using same postorder traversal causes infinite loops
- Bellman-Ford is for shortest paths, not max sums with negative cycles
- DFS without cycle checks leads to infinite recursion
Solution
Step 1: Recognize diameter depends on path length (edges), not node values.
Negative values do not affect height or path length calculations.Step 2: Confirm standard height-based diameter algorithm works unchanged.
Heights and diameter calculations rely on structure, so no changes are needed.Final Answer:
Option A -> Option AQuick Check:
Diameter depends on edges, not node values [OK]
- Confusing diameter with max sum path
- Ignoring negative nodes incorrectly
- Switching to BFS unnecessarily
