Untitled
import java.util.*; class Solution { public int deleteTreeNodes(int nodes, int[] parent, int[] value) { // Step 1: Build the tree (adjacency list) List<List<Integer>> tree = new ArrayList<>(); for (int i = 0; i < nodes; i++) { tree.add(new ArrayList<>()); } for (int i = 1; i < nodes; i++) { tree.get(parent[i]).add(i); } // Step 2: Perform DFS to compute subtree sums and count the remaining nodes return dfs(0, tree, value); } private Pair dfs(int node, List<List<Integer>> tree, int[] value) { int subtreeSum = value[node]; // Start with the node's value int cnt = 0; // Recur for all children of the current node for (int child : tree.get(node)) { Pair obj = dfs(child, tree, value); subtreesum += obj.sum; cnt+= obj.count; // Add the sum of the subtree } if (subtreeSum == 0) { return {0,0}; } // If the subtree sum is non-zero, keep the node and its subtree return {subtreesum,cnt}; // Count the current node } }
Leave a Comment