Obtain forest out of tree with even number of nodes

后端 未结 8 500
别跟我提以往
别跟我提以往 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:21

    I used BFS to travel through the nodes. First, maintain an array separately to store the total number of child nodes + 1. So, you can initially assign all the leaf nodes with value 1 in this array. Now start from the last node and count the number of children for each node. This will work in bottom to top manner and the array that stores the number of child nodes will help in runtime to optimize the code.

    Once you get the array after getting the number of children nodes for all the nodes, just counting the nodes with even number of nodes gives the answer. Note: I did not include root node in counting in final step.

提交回复
热议问题