All problems
Tree Maximum Matching Greedy
Problem
Compute the maximum matching size of a tree with n nodes.
Process nodes in reverse BFS order (leaves first): whenever a node and its parent are both unmatched, match them. This greedy is optimal on trees. edges is a list of [u, v] pairs and the tree is rooted at 0.
Hint
Matching a leaf with its parent never hurts: the parent has no better use.
Test cases
case 1
in: [4,[[0,1],[1,2],[2,3]]]
expected: 2
case 2
in: [4,[[0,1],[0,2],[0,3]]]
expected: 1
case 3
in: [3,[[0,1],[1,2]]]
expected: 1
case 4
in: [2,[[0,1]]]
expected: 1
case 5
in: [1,[]]
expected: 0
Starter codePython
def tree_max_matching(n, edges):
# Your code here
pass5 test cases · run your code against them in the editor