Search~20 min2s · 256 MBtarget O(n) time, O(n) spacetree-recursion
You work on the search box of an online catalogue. Categories are arranged in a tree: the root is the whole catalogue, and each category can have sub-categories. A category with no sub-categories is an end category, where products are listed.
Your team lead asks: "For every category, how many end categories sit under it?" An end category counts itself. The catalogue can hold 100,000 categories, and the links are given without a direction.
Write leaves_below(n, links, root).
n is the number of categories, numbered 0 to n - 1.links[i] = [a, b] joins two categories. There are exactly n - 1 links and every category can reach every other. Neither end of a link is marked as the parent.root is the whole catalogue. A category's sub-categories are its neighbours other than the one on the way to the root.n numbers. Entry i is the number of end categories in the subtree of category i, counting i itself when it is one.An end category is one with no sub-categories. The root is an end category only when n = 1.
Input: n = 8, links = [[0, 1], [0, 2], [1, 3], [1, 4], [2, 5], [5, 6], [5, 7]], root = 0
Output: [4, 2, 2, 1, 1, 2, 1, 1]The end categories are 3, 4, 6 and 7.
| Category | End categories under it | Count |
|---|---|---|
| 3, 4, 6, 7 | itself | 1 each |
| 5 | 6 and 7 | 2 |
| 1 | 3 and 4 | 2 |
| 2 | 6 and 7, through 5 | 2 |
| 0 | 3, 4, 6 and 7 | 4 |
Input: n = 3, links = [[0, 1], [1, 2]], root = 0
Output: [1, 1, 1]The root has one link, but it is not an end category: it has the sub-category 1. Only category 2 is an end category, and it lies under all three.
Input: n = 5, links = [[3, 0], [3, 1], [3, 2], [2, 4]], root = 3
Output: [1, 1, 1, 3, 1]The root is category 3, not 0. The end categories are 0, 1 and 4.
1 ≤ n ≤ 100,000len(links) = n - 1, and the links form one tree.0 ≤ root < nCounting the end categories of each category with its own walk costs the sum of all subtree sizes. For a chain of 100,000 categories that is 5,000,050,000 steps. A category's count is the sum of its sub-categories' counts, so one pass in the right order is enough. A recursive solution can also reach a depth of 100,000, which overflows the call stack in some languages.