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
- 85 lines of Java from the credited upstream file 3313.java.
- The implementation visibly relies on sequence storage, cached states.
- 4 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.
1class Solution {2 3 public int[] lastMarkedNodes(int[][] edges) {4 final int n = edges.length + 1;5 int[] ans = new int[n];6 List<Integer>[] tree = new List[n];7 8 9 Last2[] dp = new Last2[n];10 11 for (int i = 0; i < n; ++i) {12 tree[i] = new ArrayList<>();13 dp[i] = new Last2();14 }15 16 for (int[] edge : edges) {17 final int u = edge[0];18 final int v = edge[1];19 tree[u].add(v);20 tree[v].add(u);21 }22 23 dfs(tree, 0, -1, dp);24 reroot(tree, 0, -1, new Node(), dp, ans);25 return ans;26 }27 28 private record Node(int node, int time) {29 Node() {30 this(0, 0);31 }32 }33 34 private record Last2(Node last1, Node last2) {35 Last2() {36 this(new Node(), new Node());37 }38 }39 40 41 42 43 44 45 private Node dfs(List<Integer>[] tree, int u, int prev, Last2[] dp) {46 Node last1 = new Node(u, 0);47 Node last2 = new Node();48 for (final int v : tree[u]) {49 if (v == prev)50 continue;51 Node child = dfs(tree, v, u, dp);52 final int time = child.time() + 1;53 if (time > last1.time) {54 last2 = last1;55 last1 = new Node(child.node(), time);56 } else if (time > last2.time) {57 last2 = new Node(child.node(), time);58 }59 }60 dp[u] = new Last2(last1, last2);61 return last1;62 }63 64 65 66 private void reroot(List<Integer>[] tree, int u, int prev, Node last, Last2[] dp, int[] ans) {67 ans[u] = last.time() > dp[u].last1().time() ? last.node() : dp[u].last1().node();68 for (final int v : tree[u]) {69 if (v == prev)70 continue;71 Node newLast = new Node(last.node(), last.time() + 1); 72 if (dp[u].last1().node() == dp[v].last1().node()) {73 final int alternativeTime = 1 + dp[u].last2().time();74 if (alternativeTime > newLast.time())75 newLast = new Node(dp[u].last2().node(), alternativeTime);76 } else {77 final int alternativeTime = 1 + dp[u].last1().time();78 if (alternativeTime > newLast.time())79 newLast = new Node(dp[u].last1().node(), alternativeTime);80 }81 reroot(tree, v, u, newLast, dp, ans);82 }83 }84}85