- Related Questions & Answers
- Mirror of n-ary Tree in C++
- N-ary Tree Preorder Traversal in C++
- Encode N-ary Tree to Binary Tree in C++
- Number of leaf nodes in the subtree of every node of an n-ary tree in C++
- N-ary Tree Level Order Traversal in C++
- Serialize and Deserialize N-ary Tree in C++
- Depth of an N-Ary tree in C++?
- Next Larger element in n-ary tree in C++
- Depth of an N-Ary tree in C++ Program
- Preorder Traversal of N-ary Tree Without Recursion in C++
- m-ary tree
- Print all leaf nodes of an n-ary tree using DFS in C++
- Number of nodes greater than a given value in n-ary tree in C++
- N-ary Relationship in Database
- Find largest subtree sum in a tree in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

In this problem, we are given an adjacency list that denotes an n-ary tree. Our task is to find the number of *even size subtree in n-ary tree. *

**N-ary tree**** is defined as a collection of nodes normally represented hierarchically in the following manner.**

**The tree is started at the root node.**

**Each node of the tree maintains a list of pointers to its child nodes.**

**The number of child nodes is less than or equal to m.**

**Input: **

**Output: **4

**Explanation: **

Tree rooted with 7 has an even size.

Tree rooted with 2 has an even size.

Tree rooted with 0 has an even size.

Tree rooted with 3 has an even size.

A simple approach is by counting all child nodes for a given node, if it is even increase the evenTreeCount. For this we will use DFS, and find the length of SubTree for the given node.

We can do this using a single *traversal on the tree. *By recursively finding the size of subtrees of each child node and then check the size and if its is even, increase the evenTreeCount otherwise leave it.

#include <bits/stdc++.h> using namespace std; int countEventSizeSubTree(vector<int> adj[], int n, int v, int& EvenCount){ int size = 1; for (auto ele : adj[v]) { size += countEventSizeSubTree(adj, n, ele, EvenCount); } if (size % 2 == 0) EvenCount++; return size; } int main(){ int n; n = 10; vector<int> adj[n + 1]; adj[7].push_back(2); adj[7].push_back(9); adj[2].push_back(0); adj[2].push_back(1); adj[9].push_back(3); adj[3].push_back(8); adj[0].push_back(5); int EvenCount = 0; countEventSizeSubTree(adj, n, 1, EvenCount); cout<<"Even Size SubTree are "<<EvenCount; return 0; }

Even Size SubTree are 0

Advertisements