- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Even size subtree in n-ary tree in C++
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.
Let’s take an example to understand the problem,
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.
Solution Approach −
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.
Program to illustrate the working of our solution,
Example
#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; }
Output −
Even Size SubTree are 0
- Related Articles
- Number of leaf nodes in the subtree of every node of an n-ary tree in C++
- Mirror of n-ary Tree in C++
- N-ary Tree Preorder Traversal in C++
- Encode N-ary Tree to Binary 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++
- 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++
- Find the Number of Siblings of a Given Node in N-ary Tree using C++
- Program to make a copy of a n-ary tree in Python
- Program to find the root of a n-ary tree in Python
