MediumNo. 2445LeetCode Premium
Number of Nodes With Value One — LeetCode 2445 Python Solution
- Pattern
- Tree Traversal
- Topics
- Tree, Depth-First Search, Breadth-First Search, Array, Binary Tree
- Reading time
- 3 min
- Source
- leetcode.com
The problem
There is an undirected connected tree with n nodes labeled from 1 to n and n - 1 edges. You are given the integer n.
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.
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
- Time
- O(n × log n)
- Space · auxiliary
- O(n)
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2445. Number of Nodes With Value One is filed here because LeetCode tags it Tree and Binary 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
| No. | Problem | Difficulty |
|---|---|---|
| 2458 | Height of Binary Tree After Subtree Removal Queries | Hard |
| 0100 | Same Tree | Easy |
| 0101 | Symmetric Tree | Easy |
| 0104 | Maximum Depth of Binary Tree | Easy |
| 0111 | Minimum Depth of Binary Tree | Easy |
| 0112 | Path Sum | Easy |
Frequently asked questions
- How hard is LeetCode 2445. Number of Nodes With Value One?
LeetCode 2445. Number of Nodes With Value One is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2445. Number of Nodes With Value One?
The Python solution on this page runs in O(n × log n).
- What is the space complexity of LeetCode 2445. Number of Nodes With Value One?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2445. Number of Nodes With Value One cover?
LeetCode 2445. Number of Nodes With Value One is tagged Tree, Depth-First Search, Breadth-First Search, Array and Binary Tree on LeetCode.
- Is LeetCode 2445. Number of Nodes With Value One a premium problem?
Yes. LeetCode 2445. Number of Nodes With Value One is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.