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.
Example:
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 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:
C++
#include <bits/stdc++.h>
using namespace std;
int numberOfNodes(int n, vector<int>& queries)
{
// f[i] = 1 means we need to flip all values in the
// subtree of the node i
vector<int> f(n + 1);
// if we flip the node even times, the value would be
// same as the original value e.g. 0 (original value) ->
// 1 -> 0 if we flip the node odd times, the value would
// be the the opposite of the original value e.g. 0
// (original value) -> 1 -> 0 -> 1 therefore, we can
// first process the queries to obtain the final flips
for (auto q : queries)
f[q] ^= 1;
function<int(int, int)> dfs = [&](int u, int v) {
// u is the current node label
// if u is greater than n, then return 0
if (u > n)
return 0;
// do we need to flip the node u?
// we flip the value if f[u] is 1
v ^= f[u];
// the result would be the value of u, i.e. v
// plus the result of the left subtree, i.e dfs(u *
// 2, v) plus the result of the right subtree, i.e.
// dfs(u * 2 + 1, v)
return v + dfs(u * 2, v) + dfs(u * 2 + 1, v);
};
// we start from node 1 with inital value 0
return dfs(1, 0);
}
// Driver code
int main()
{
int n = 7;
vector<int> queries = { 3, 1, 4, 1, 5, 9, 2, 6 };
int result = numberOfNodes(n, queries);
cout << result << endl;
return 0;
}
Java
import java.util.List;
import java.util.function.BiFunction;
public class NumberOfNodes {
public static int numberOfNodes(int n,
List<Integer> queries)
{
// f[i] = 1 means we need to flip all values in the
// subtree of the node i
int[] f = new int[n + 1];
// If we flip the node even times, the value would
// be same as the original value If we flip the node
// odd times, the value would be the opposite of the
// original value Therefore, we can first process
// the queries to obtain the final flips
for (int q : queries) {
if (q <= n) {
f[q] ^= 1;
}
}
// Define the dfs function using a lambda expression
BiFunction<Integer, Integer, Integer> dfs
= new BiFunction<>() {
@Override
public Integer apply(Integer u, Integer v)
{
// u is the current node label
// if u is greater than n, then return
// 0
if (u > n)
return 0;
// do we need to flip the node u?
// we flip the value if f[u] is 1
v ^= f[u];
// the result would be the value of u,
// i.e. v plus the result of the left
// subtree, i.e dfs(u * 2, v) plus the
// result of the right subtree, i.e.
// dfs(u * 2 + 1, v)
return v + this.apply(u * 2, v)
+ this.apply(u * 2 + 1, v);
}
};
// We start from node 1 with initial value 0
return dfs.apply(1, 0);
}
public static void main(String[] args)
{
int n = 7;
List<Integer> queries
= List.of(3, 1, 4, 1, 5, 9, 2, 6);
int result = numberOfNodes(n, queries);
System.out.println(result);
}
}
// This code is contributed by Akshita
Python
def number_of_nodes(n, queries):
# f[i] = 1 means we need to flip all values in the
# subtree of the node i
f = [0] * (n + 1) # Ensure f has enough space
# If we flip the node even times, the value would be
# the same as the original value e.g., 0 (original value) ->
# 1 -> 0 if we flip the node odd times, the value would
# be the opposite of the original value e.g., 0
# (original value) -> 1 -> 0 -> 1. Therefore, we can
# first process the queries to obtain the final flips
for q in queries:
if q <= n: # Check if query index is within range
f[q] ^= 1
def dfs(u, v):
# u is the current node label
# If u is greater than n, then return 0
if u > n:
return 0
# Do we need to flip the node u?
# We flip the value if f[u] is 1
v ^= f[u]
# The result would be the value of u, i.e., v
# plus the result of the left subtree, i.e., dfs(u *
# 2, v) plus the result of the right subtree, i.e.,
# dfs(u * 2 + 1, v)
return v + dfs(u * 2, v) + dfs(u * 2 + 1, v)
# We start from node 1 with initial value 0
return dfs(1, 0)
# Driver code
if __name__ == "__main__":
n = 7
queries = [3, 1, 4, 1, 5, 9, 2, 6]
result = number_of_nodes(n, queries)
print(result)
# This code is contributed by Shivam Gupta
JavaScript
function numberOfNodes(n, queries) {
// f[i] = 1 means we need to flip all values in the
// subtree of the node i
let f = new Array(n + 2).fill(0); // Increase size to n + 2
// if we flip the node even times, the value would be
// same as the original value e.g. 0 (original value) ->
// 1 -> 0 if we flip the node odd times, the value would
// be the the opposite of the original value e.g. 0
// (original value) -> 1 -> 0 -> 1 therefore, we can
// first process the queries to obtain the final flips
for (let q of queries) {
f[q] ^= 1;
}
function dfs(u, v) {
// u is the current node label
// if u is greater than n, then return 0
if (u > n) {
return 0;
}
// do we need to flip the node u?
// we flip the value if f[u] is 1
v ^= f[u];
// the result would be the value of u, i.e. v
// plus the result of the left subtree, i.e dfs(u *
// 2, v) plus the result of the right subtree, i.e.
// dfs(u * 2 + 1, v)
return v + dfs(u * 2, v) + dfs(u * 2 + 1, v);
}
// we start from node 1 with inital value 0
return dfs(1, 0);
}
// Driver code
let n = 7;
let queries = [3, 1, 4, 1, 5, 9, 2, 6];
let result = numberOfNodes(n, queries);
console.log(result);
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.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read