The Number of Nodes in the Sub-Tree With the Same Label problem gives you a rooted tree where each node has a character label. For each node, count how many nodes in its subtree (including itself) have the same label. Return an array of counts. This coding problem uses post-order DFS with character frequency propagation.
Samsung and Uber ask this to test post-order DFS where each node aggregates information from its children. The key technique is returning a character frequency map from each subtree DFS and combining children's counts at the parent. The BFS, hash table, counting, DFS, and tree interview pattern is the core.
Post-order DFS with frequency maps. Each DFS call returns a character count array (or dict) for its subtree. For each node: start with a count of 1 for its own label, then add counts from all children's returned maps. Store the count for the current node's own label in the result. Return the combined count map to the parent.
Tree: node 0 labeled 'a' → children [1('b'), 2('a')]. Node 1 → child [3('b')].
Post-order DFS "propagate information from subtree to parent" is a reusable pattern. For this problem, the aggregation is character frequency addition. The returned frequency map acts as the subtree's summary. Practice similar problems: subtree sum, subtree node count, maximum depth with constraints. The pattern is always: recurse to children, combine their results, compute the current node's contribution, return to parent.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Clone N-ary Tree | Medium | Solve | |
| Minimum Time to Collect All Apples in a Tree | Medium | Solve | |
| Employee Importance | Medium | Solve | |
| All Nodes Distance K in Binary Tree | Medium | Solve | |
| Amount of Time for Binary Tree to Be Infected | Medium | Solve |