Approach
Depth-first search
For Find the Last Marked Nodes in Tree, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 82 lines of C++ from the credited upstream file 3313.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 3 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1struct Node {2 int node = 0; 3 int time = 0; 4};5 6struct Last2 {7 Node last1; 8 Node last2; 9};10 11class Solution {12 public:13 14 vector<int> lastMarkedNodes(vector<vector<int>>& edges) {15 const int n = edges.size() + 1;16 vector<int> ans(n);17 vector<vector<int>> tree(n);18 19 20 vector<Last2> dp(n);21 22 for (const vector<int>& edge : edges) {23 const int u = edge[0];24 const int v = edge[1];25 tree[u].push_back(v);26 tree[v].push_back(u);27 }28 29 dfs(tree, 0, -1, dp);30 reroot(tree, 0, -1, Node(), dp, ans);31 return ans;32 }33 34 private:35 36 37 38 39 40 Node dfs(const vector<vector<int>>& tree, int u, int prev,41 vector<Last2>& dp) {42 Node last1(u, 0);43 Node last2;44 for (const int v : tree[u]) {45 if (v == prev)46 continue;47 Node child = dfs(tree, v, u, dp);48 const int time = child.time + 1;49 if (time > last1.time) {50 last2 = last1;51 last1 = Node(child.node, time);52 } else if (time > last2.time) {53 last2 = Node(child.node, time);54 }55 }56 dp[u] = {last1, last2};57 return last1;58 }59 60 61 62 void reroot(const vector<vector<int>>& tree, int u, int prev,63 const Node& last, vector<Last2>& dp, vector<int>& ans) {64 ans[u] = last.time > dp[u].last1.time ? last.node : dp[u].last1.node;65 for (const int v : tree[u]) {66 if (v == prev)67 continue;68 Node newLast(last.node, last.time + 1);69 if (dp[u].last1.node == dp[v].last1.node) {70 const int alternativeTime = 1 + dp[u].last2.time;71 if (alternativeTime > newLast.time)72 newLast = Node(dp[u].last2.node, alternativeTime);73 } else {74 const int alternativeTime = 1 + dp[u].last1.time;75 if (alternativeTime > newLast.time)76 newLast = Node(dp[u].last1.node, alternativeTime);77 }78 reroot(tree, v, u, newLast, dp, ans);79 }80 }81};82