

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Number of leaf nodes in the subtree of every node of an n-ary tree in C++
In this tutorial, we are going to write a program that finds the number of leaf nodes for every node in the n-ary tree.
Given a n-ary tree, we have to find the number of leaf nodes for every subtree. Let's see an example.
Input
N = 8 tree = [[2, 3], [], [4, 5, 6], [7, 8], [], [], [], []]
Output
1->5 2->1 3->4 4->2 5->1 6->1 7->1 8->1
Algorithm
Initialise the n-ary tree with tree you like.
Use the DFS to traverse through the tree.
Maintain an array to store the count of each node leaf nodes count.
Increment the count of leaf node after the recursive call to DFS.
Print all node with leaf nodes count.
Implementation
Following is the implementation of the above algorithm in C++
#include <bits/stdc++.h> using namespace std; void insertNode(int x, int y, vector<int> tree[]) { tree[x].push_back(y); } void DFS(int node, int leaf[], int visited[], vector<int> tree[]) { leaf[node] = 0; visited[node] = 1; for (auto it : tree[node]) { if (!visited[it]) { DFS(it, leaf, visited, tree); leaf[node] += leaf[it]; } } if (!tree[node].size()) { leaf[node] = 1; } } int main() { int N = 8; vector<int> tree[N + 1]; insertNode(1, 2, tree); insertNode(1, 3, tree); insertNode(3, 4, tree); insertNode(3, 5, tree); insertNode(3, 6, tree); insertNode(4, 7, tree); insertNode(4, 8, tree); int leaf[N + 1]; int visited[N + 1]; for (int i = 0; i <= N; i++) { visited[i] = 0; } DFS(1, leaf, visited, tree); for (int i = 1; i <= N; i++) { cout << i << "->" << leaf[i] << endl; } return 0; }
Output
If you run the above code, then you will get the following result.
1->5 2->1 3->4 4->2 5->1 6->1 7->1 8->1
- Related Questions & Answers
- Print all leaf nodes of an n-ary tree using DFS in C++
- Find the Number of Siblings of a Given Node in N-ary Tree using C++
- Depth of an N-Ary tree in C++?
- Even size subtree in n-ary tree in C++
- Number of nodes greater than a given value in n-ary tree in C++
- Depth of an N-Ary tree in C++ Program
- Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree in C++
- Print the nodes of binary tree as they become the leaf node in C++ Programming.
- Mirror of n-ary Tree in C++
- Python Program to Count Number of Leaf Node in a Tree
- Product of all leaf nodes of binary tree in C++
- Find the Number of Ways to Traverse an N-ary Tree using C++
- Python Program to Count Number of Non Leaf Nodes of a given Tree
- Find the sum of left leaf nodes of a given Binary Tree in C++
- Program to find leaf and non-leaf nodes of a binary tree in Python
Advertisements