Cutting Edges of a Tree

Given a tree with n nodes. You want to cut the maximum number of edges so that every resulting piece (component) (A component is a connected group of nodes. Its size is the number of nodes in it.) has an EVEN number of nodes.

If it is impossible to make every piece even, output -1. Otherwise, your task is to output the maximum number of cuts.

Array edges: A 2D array of [u, v] pairs representing the undirected edges. Use this to build a 1-indexed adjacency list.

Example 1:

Input: n = 4, edges = [[2, 4], [4, 1], [3, 1]]

Output: 1

Explanation: The tree has 4 nodes. If we cut the edge between 1 and 4, we get two components: {1, 3} (size 2) and {2, 4} (size 2). Both are even. Since we made 1 cut, the answer is 1.

Example 2:

Input: n = 3, edges = [[1, 2], [1, 3]]

Output: -1

Explanation: The total number of nodes is 3. No matter how you cut it, the sum of the sizes of the components will be 3. You cannot partition an odd number into a sum of even numbers. Therefore, it's impossible.

Now Your Turn!

Pick the correct output for the given input

Input: n = 6, edges [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= n <= 105
  • The provided edges are guaranteed to form a single, valid connected tree.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
int cutEmAll(int n, vector<vector<int>>& edges) {
// Write your code here
return 0;
}
};
 
Test Case

Input:

Edges
N