Today I have solved the problem in javascript
You are given a tree with an even number of nodes. Consider each connection between a parent and child node to be an "edge". You would like to remove some of these edges, such that the disconnected subtrees that remain each have an even number of nodes.
For example, suppose your input was the following tree:
1
/ \
2 3
/ \
4 5
/ | \
6 7 8
In this case, removing the edge (3, 4) satisfies our requirement.
Write a function that returns the maximum number of edges you can remove while still satisfying this requirement.
const tree = [
[1],
[0, 3],
[5],
[1, 4, 5],
[3],
[2, 3, 6, 7, 8],
[5],
[5],
[5]
];
const result = maxEdgesToRemove(tree);
function maxEdgesToRemove(tree) {
const dfs = (node, parent, evenCount) => {
let edgesToRemove = 0;
for (const child of tree[node]) {
if (child !== parent) {
edgesToRemove += dfs(child, node, evenCount);
}
}
if (evenCount[node] % 2 !== 0) {
evenCount[parent]++;
edgesToRemove++;
}
return edgesToRemove;
};
const n = tree.length;
const evenCount = new Array(n).fill(1);
return dfs(0, -1, evenCount);
}
console.log(result);
Output:
8
Comments
Post a Comment