- 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
Print all leaf nodes of an n-ary tree using DFS in C++
In this problem, we are given a 2-D array containing the edge of an n-ary where edge defines the edge of the n-ary tree. We have to print all the leaf nodes of the created a-ary tree.
The n-ary tree is a tree with has maximum n children i.e. a node can have 1, 2, ...n child nodes.
Let’s see an example to understand the problem −
Input: edge[][] = {{5,8}, {5,6}, {8,1}, {8,4}, {6,7}} Output: 1 4 7
Explanation − let's create a tree using the edge array −
The leaf nodes of this tree are 1, 4, 7.
To solve this problem, we will traverse the tree using DFS (it will find the leaf node of every subtree). Also, visited nodes of the array are marked. If the node has a child (if not leaf node), we will flag the value and print nodes without a child node.
Example
This program shows the implementation of our solution −
#include <bits/stdc++.h> using namespace std; void DFS(list<int> t[], int node, int parent) { int flag = 0; for (auto ir : t[node]) { if (ir != parent) { flag = 1; DFS(t, ir, node); } } if (flag == 0) cout<<node<<"\t"; } int main() { list<int> t[1005]; pair<int, int> edges[] = { { 1, 2 }, { 1, 3 }, { 2, 4 }, { 3, 5 }, { 3, 6 }, { 3, 7 }, { 6, 8 } }; int cnt = sizeof(edges) / sizeof(edges[0]); int node = cnt + 1; for (int i = 0; i < cnt; i++) { t[edges[i].first].push_back(edges[i].second); t[edges[i].second].push_back(edges[i].first); } cout<<"Leaf nodes of the tree are:\n"; DFS(t, 1, 0); return 0; }
Output
Leaf nodes of the tree are − 4 5 8 7
- Related Articles
- Number of leaf nodes in the subtree of every node of an n-ary tree in C++
- Print all leaf nodes of a binary tree from right to left in C++
- Print All Leaf Nodes of a Binary Tree from left to right using Iterative Approach in C++
- Product of all leaf nodes of binary tree in C++
- Depth of an N-Ary tree in C++?
- Depth of an N-Ary tree in C++ Program
- Number of nodes greater than a given value in n-ary tree in C++
- Print leaf nodes in binary tree from left to right using one stack in C++
- Mirror of n-ary Tree in C++
- Print all odd nodes of Binary Search Tree in C++
- Print all internal nodes of a Binary tree in C++
- Print all even nodes of Binary Search Tree in C++
- Find the Number of Ways to Traverse an N-ary Tree using C++
- Print the nodes of binary tree as they become the leaf node in C++ Programming.
- Print all full nodes in a Binary Tree in C++

Advertisements