Leetcode #2445: Number of Nodes With Value One
In this guide, we solve Leetcode #2445 Number of Nodes With Value One in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
There is an undirected connected tree with n nodes labeled from 1 to n and n - 1 edges. You are given the integer n.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Tree, Depth-First Search, Breadth-First Search, Array, Binary Tree
Intuition
We need to explore a structure deeply before backing up, which suits DFS.
DFS keeps local context on the call stack and is easy to implement recursively.
Approach
Define a recursive DFS that carries the necessary state.
Combine child results as the recursion unwinds.
Steps:
- Define a recursive DFS with state.
- Visit children and combine results.
- Return the final aggregation.
Example
Input: n = 5 , queries = [1,2,5]
Output: 3
Explanation: The diagram above shows the tree structure and its status after performing the queries. The blue node represents the value 0, and the red node represents the value 1.
After processing the queries, there are three red nodes (nodes with value 1): 1, 3, and 5.
Python Solution
class Solution:
def numberOfNodes(self, n: int, queries: List[int]) -> int:
def dfs(i):
if i > n:
return
tree[i] ^= 1
dfs(i << 1)
dfs(i << 1 | 1)
tree = [0] * (n + 1)
cnt = Counter(queries)
for i, v in cnt.items():
if v & 1:
dfs(i)
return sum(tree)
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.