Number of Nodes With Value One — LeetCode 2445 Python Solution

MediumLeetCode PremiumTreeDepth-First SearchBreadth-First SearchArrayBinary Tree
Problem
#2445
Reading time
3 min

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

Python
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

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

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

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 \times \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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview