2440. Create Components With Same Value
Explanation:
To solve this problem, we can use a depth-first search (DFS) algorithm to traverse the tree and compute the sum of values in each subtree. We can keep track of the count of edges that need to be deleted to make the subtree have the same value. If all subtrees under a node have the same value, we can delete all edges connecting those subtrees except for one, which will be the edge connecting the current node to its parent.
- Perform a DFS traversal starting from the root node.
- At each node, recursively calculate the sum of values in all its child subtrees.
- If the sum of values in all child subtrees is the same, we can delete all edges connecting those subtrees except one.
- Keep track of the count of edges that need to be deleted to make the subtree have the same value.
Time Complexity: O(n), where n is the number of nodes in the tree. Space Complexity: O(n).
:
class Solution {
private int result = 0;
public int deleteTreeEdges(int[] nums, int[][] edges) {
Map<Integer, List<Integer>> graph = new HashMap<>();
for (int[] edge : edges) {
graph.computeIfAbsent(edge[0], k -> new ArrayList<>()).add(edge[1]);
graph.computeIfAbsent(edge[1], k -> new ArrayList<>()).add(edge[0]);
}
dfs(0, -1, nums, graph);
return result;
}
private int dfs(int node, int parent, int[] nums, Map<Integer, List<Integer>> graph) {
int sum = nums[node];
List<Integer> childSums = new ArrayList<>();
for (int child : graph.getOrDefault(node, new ArrayList<>())) {
if (child == parent) continue;
int childSum = dfs(child, node, nums, graph);
sum += childSum;
childSums.add(childSum);
}
for (int childSum : childSums) {
if (childSum * 2 == sum) {
result++;
}
}
return sum;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.