Obtain forest out of tree with even number of nodes

后端 未结 8 497
别跟我提以往
别跟我提以往 2021-02-03 20:31

I\'m stuck on a code challenge, and I want a hint.

PROBLEM: You are given a tree data structure (without cycles) and are asked to remo

8条回答
  •  情歌与酒
    2021-02-03 21:12

    If you observe the input, you can see that it is quite easy to count the number of nodes under each node. Consider (a b) as the edge input, in every case, a is the child and b is the immediate parent. The input always has edges represented bottom-up.

    So its essentially the number of nodes which have an even count(Excluding the root node). I submitted the below code on Hackerrank and all the tests passed. I guess all the cases in the input satisfy the rule.

    def find_edges(count):
        root = max(count)
    
        count_even = 0
    
        for cnt in count:
            if cnt % 2 == 0:
                count_even += 1
    
        if root % 2 == 0:
            count_even -= 1
    
        return count_even
    
    def count_nodes(edge_list, n, m):
        count = [1 for i in range(0, n)]
    
        for i in range(m-1,-1,-1):
            count[edge_list[i][1]-1] += count[edge_list[i][0]-1]
    
    return find_edges(count)
    

提交回复
热议问题