Problem solution · Python

Number of Nodes in the Sub Tree with the Same Label

Number of Nodes in the Sub Tree with the Same Label: a Python solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Depth-first search
Source
Kamyu LeetCode Solutions
Length
79 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Depth-first search

For Number of Nodes in the Sub Tree with the Same Label, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. Combine child results or undo the choice when the branch finishes.

Code notes

  • 79 lines of Python from the credited upstream file number-of-nodes-in-the-sub-tree-with-the-same-label.py.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected, together with recursive traversal.

Complexity

Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeNumber of Nodes in the Sub Tree with the Same Label · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(n)# Space: O(h) class Solution(object):    def countSubTrees(self, n, edges, labels):        """        :type n: int        :type edges: List[List[int]]        :type labels: str        :rtype: List[int]        """        def iter_dfs(labels, adj, node, parent, result):            stk = [(1, (node, parent, [0]*26))]            while stk:                step, params = stk.pop()                if step == 1:                    node, parent, ret = params                    stk.append((4, (node, ret)))                    stk.append((2, (node, parent, reversed(adj[node]), ret)))                elif step == 2:                    node, parent, it, ret = params                    child = next(it, None)                    if not child or child == parent:                        continue                    ret2 = [0]*26                    stk.append((2, (node, parent, it, ret)))                    stk.append((3, (ret2, ret)))                    stk.append((1, (child, node, ret2)))                elif step == 3:                    ret2, ret = params                    for k in xrange(len(ret2)):                        ret[k] += ret2[k]                else:                    node, ret = params                    ret[ord(labels[node]) - ord('a')] += 1                    result[node] += ret[ord(labels[node]) - ord('a')]                adj = [[] for _ in xrange(n)]        for u, v in edges:            adj[u].append(v)            adj[v].append(u)        result = [0]*n        iter_dfs(labels, adj, 0, -1, result)        return result  # Time:  O(n)# Space: O(h)import collections  class Solution2(object):    def countSubTrees(self, n, edges, labels):        """        :type n: int        :type edges: List[List[int]]        :type labels: str        :rtype: List[int]        """        def dfs(labels, adj, node, parent, result):            count = [0]*26            for child in adj[node]:                if child == parent:                    continue                new_count = dfs(labels, adj, child, node, result)                for k in xrange(len(new_count)):                    count[k] += new_count[k]            count[ord(labels[node]) - ord('a')] += 1            result[node] = count[ord(labels[node]) - ord('a')]            return count                adj = [[] for _ in xrange(n)]        for u, v in edges:            adj[u].append(v)            adj[v].append(u)        result = [0]*n        dfs(labels, adj, 0, -1, result)        return result 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗