Count the nodes in the given tree whose weight is even parity
Last Updated : 11 Jul, 2025
Given a tree and the weights of all the nodes, the task is to count the number of nodes whose weights are even parity i.e. whether the count of set bits in them is even. Examples:
Approach: Perform dfs on the tree and for every node, check if its weight is even parity or not. If yes then increment count.
Steps to solve the problem:
Initialize ans to 0.
Define a function isEvenParity(x) that takes an integer x and returns true if the count of set bits in x is even and false otherwise.
Define a function dfs(node, parent) that performs depth-first search on the graph.
Within the dfs function: a. Check if the weight of the current node has even parity using the isEvenParity function. If it does, increment ans by 1. b. For each neighbor to of node in the graph, if it is not equal to the parent, recursively call dfs with to as the node and node as the parent.
Return ans as the final result.
Below is the implementation of the above approach:
Output:
3
Time Complexity: O(N). In DFS, every node of the tree is processed once and hence the complexity due to the DFS is O(N) for N nodes in the tree. Therefore, the time complexity is O(N).
Auxiliary Space: O(1). Any extra space is not required, so the space complexity is constant.