Count Number of Nodes With Value One in Undirected Tree
Last Updated : 31 May, 2024
Given an undirected connected tree with n nodes labeled from 1 to n, and an integer array of queries[]. Initially, all nodes have a value of 0. For each query in the array, you need to flip the values of all nodes in the subtree of the node with the corresponding label. The parent of a node with label v is the node with label floor(v/2), and the root has label 1.
Note: Return the total number of nodes with a value of 1 after processing all the queries.
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 green node represents the value 0, and the grey node represents the value 1. After processing the queries, there are three grey nodes (nodes with value 1): 1, 3, and 5.
Input: n = 3, queries = [2,3,3] Output: 1
Approach:
The main idea is that flipping a node's value twice brings it back to its original state. Therefore, we can simply track the number of times each node is flipped by the queries. If a node is flipped an odd number of times, its final value will be 1; otherwise, it will be 0.
We can use a depth-first search (DFS) to traverse the tree and count the number of flips for each node. For each node, we check if it needs to be flipped based on the query information. Then, we recursively explore its left and right subtrees, keeping track of the cumulative flips. Finally, we return the sum of the node's value and the values of its subtrees, which represents the total number of nodes with value 1 in its subtree.
Steps-by-step approach:
Initialize:
Create an array f of size n + 1, where n is the number of nodes in the tree.
Initialize all elements in f to 0.
Create a vector queries to store the queries.
Process Queries:
For each query in queries:
Flip the value of f[query] (0 becomes 1, 1 becomes 0).
Perform Depth-First Search (DFS):
Define a recursive function dfs(u, v):
If u is greater than n, return 0.
Flip the value of v based on f[u].
Recursively call dfs(u * 2, v) to explore the left subtree.
Recursively call dfs(u * 2 + 1, v) to explore the right subtree.
Return the sum of v (the value of the current node) and the results of the left and right subtrees.
Start DFS:
Call dfs(1, 0) to start the DFS from the root node (node 1) with an initial value of 0.
Return Result:
The result of dfs(1, 0) is the total number of nodes with value 1 in the tree. Return this value.
Below is the implementation of the above approach:
Output
3
Time complexity: O(n), where n is the number of nodes in the tree. Auxiliary Space: O(n), due to the use of the f array and the recursion stack.