Python 3   ||  recursion   ||   T/S: 98% / 97%
\nclass Solution:\n    def placedCoins(self, edges: List[List[int]], cost: List[int]) -> List[int]:\n        \n        ans, graph = [1] * len(cost), defaultdict
```\nclass Solution:\n    def placedCoins(self, edges: List[List[int]], cost: List[int]) -> List[int]:\n        \n        ans, graph = [1] * len(cost), defaultdict(list)\n\n        for  a, b in edges:\n                graph[a].append(b)\n                graph[b].append(a)\n\n        def dp(node: int) -> List[int]:\n\n            coins, cost[node] = [cost[node]], 0\n\n            for child in graph[node]:\n                if cost[child] == 0: continue\n                coins.extend(dp(child))\n            coins.sort()\n\n            if len(coins) >= 3:\n                (n1, n2), (p3, p2, p1) = coins[:2], coins[-3:]\n                ans[node] = max(0, n1 * n2 * p1, p1 * p2 * p3)\n\n            if len(coins) <= 5: return coins\n            return [n1, n2, p3, p2, p1]\n\n        dp(0)\n\n        return ans\n```\n[https://leetcode.com/problems/find-number-of-coins-to-place-in-tree-nodes/submissions/1148296052/](http://)\n\n\n\nI could be wrong, but I think that time complexity is *O*(*N*log*N*) and space complexity is *O*(*N*^2), in which *N* ~ number of nodes in the tree.
['Python3']