Tree Matching
You are given an undirected tree with n nodes labeled from 1 to n.
A matching is a set of edges such that no two chosen edges share a common node. In other words, every node can be part of at most one selected edge.
Return the maximum number of edges that can be chosen in such a matching.
Example 1:
Input: n = 5, edges = [[1,2],[1,3],[3,4],[3,5]]
Output: 2
Explanation:
One valid maximum matching is selecting edges [1,2] and [3,4].
No node is used more than once, so this is a valid matching.
It is not possible to select 3 edges because at least one node would have to belong to more than one chosen edge.
Example 2:
Input: n = 6, edges = [[1,2],[2,3],[3,4],[4,5],[5,6]]
Output: 3
Explanation:
A maximum matching is [1,2], [3,4], and [5,6].
These 3 edges do not share any endpoints, so the matching size is 3.
Now Your Turn!
Pick the correct output for the given inputInput: n = 4, edges = [[1,2],[2,3],[3,4]]
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 <= 2 * 105
- edges.length == n - 1
- edges[i].length == 2
- 1 <= edges[i][0], edges[i][1] <= n
- edges represents a valid tree