Count Number of Possible Root Nodes — LeetCode 2581 Python Solution
- Problem
- #2581
- Pattern
- Tree Traversal
- Reading time
- 6 min
- Source
- leetcode.com
The problem
Alice has an undirected tree with n nodes labeled from 0 to n - 1. The tree is represented as a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
Example
- Input
- edges = [[0,1],[1,2],[1,3],[4,2]], guesses = [[1,3],[0,1],[1,0],[2,4]], k = 3
- Output
- 3
- Explanation
- Root = 0, correct guesses = [1,3], [0,1], [2,4]
Python solution
class Solution:
def rootCount(
self, edges: List[List[int]], guesses: List[List[int]], k: int
) -> int:
def dfs1(i, fa):
nonlocal cnt
for j in g[i]:
if j != fa:
cnt += gs[(i, j)]
dfs1(j, i)
def dfs2(i, fa):
nonlocal ans, cnt
ans += cnt >= k
for j in g[i]:
if j != fa:
cnt -= gs[(i, j)]
cnt += gs[(j, i)]
dfs2(j, i)
cnt -= gs[(j, i)]
cnt += gs[(i, j)]
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
g[b].append(a)
gs = Counter((u, v) for u, v in guesses)
cnt = 0
dfs1(0, -1)
ans = 0
dfs2(0, -1)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n + m) |
| Space | O(n + m), where n and m are the lengths of edges and guesses respectively auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2581. Count Number of Possible Root Nodes is filed here because LeetCode tags it Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2581. Count Number of Possible Root Nodes?
- LeetCode 2581. Count Number of Possible Root Nodes is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2581. Count Number of Possible Root Nodes?
- The Python solution on this page runs in O(n + m).
- What is the space complexity of LeetCode 2581. Count Number of Possible Root Nodes?
- The Python solution on this page uses O(n + m), where n and m are the lengths of edges and guesses respectively auxiliary space.
- What topics does LeetCode 2581. Count Number of Possible Root Nodes cover?
- LeetCode 2581. Count Number of Possible Root Nodes is tagged Tree, Depth-First Search, Array, Hash Table and Dynamic Programming on LeetCode.