Related Articles
Number of leaf nodes in the subtree of every node of an n-ary tree
• Last Updated : 24 Mar, 2020

Given an N-ary tree, print the number of leaf nodes in the subtree of every node.

Examples:

```Input:
1
/    \
2      3
/  |   \
4   5    6
Output:
The node 1 has 4 leaf nodes
The node 2 has 1 leaf nodes
The node 3 has 3 leaf nodes
The node 4 has 1 leaf nodes
The node 5 has 1 leaf nodes
The node 6 has 1 leaf nodes
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: The idea is to perform DFS traversal on the given tree and for every node keep an array leaf[] to store the count of leaf nodes in the subtree below it.

Now, while recurring down the tree, if a leaf node is found set it’s leaf[i] value to 1 and return back in upward direction. Now, every time while returning back from the function call to upward, add the leaf nodes of the node below it.

Once, the DFS traversal is completed we will have the count of leaf nodes in the array leaf[].

Below is the implementation of the above approach:

## C++

 `// C++ program to print the number of``// leaf nodes of every node``#include ``using` `namespace` `std;`` ` `// Function to insert edges of tree``void` `insert(``int` `x, ``int` `y, vector<``int``> adjacency[])``{``    ``adjacency[x].push_back(y);``}`` ` `// Function to run DFS on a tree``void` `dfs(``int` `node, ``int` `leaf[], ``int` `vis[],``         ``vector<``int``> adjacency[])``{``    ``leaf[node] = 0;``    ``vis[node] = 1;`` ` `    ``// iterate on all the nodes``    ``// connected to node``    ``for` `(``auto` `it : adjacency[node]) {`` ` `        ``// If not visited``        ``if` `(!vis[it]) {``            ``dfs(it, leaf, vis, adjacency);``            ``leaf[node] += leaf[it];``        ``}``    ``}`` ` `    ``if` `(!adjacency[node].size())``        ``leaf[node] = 1;``}`` ` `// Function to print number of``// leaf nodes of a node``void` `printLeaf(``int` `n, ``int` `leaf[])``{``    ``// Function to print leaf nodes``    ``for` `(``int` `i = 1; i <= n; i++) {``        ``cout << ``"The node "` `<< i << ``" has "``             ``<< leaf[i] << ``" leaf nodes\n"``;``    ``}``}`` ` `// Driver Code``int` `main()``{``    ``// Given N-ary Tree`` ` `    ``/*     1 ``         ``/   \``        ``2     3``            ``/ | \``            ``4 5 6 */`` ` `    ``int` `N = 6; ``// no of nodes``    ``vector<``int``> adjacency[N + 1]; ``// adjacency list for tree`` ` `    ``insert(1, 2, adjacency);``    ``insert(1, 3, adjacency);``    ``insert(3, 4, adjacency);``    ``insert(3, 5, adjacency);``    ``insert(3, 6, adjacency);`` ` `    ``int` `leaf[N + 1]; ``// Store count of leaf in subtree of i``    ``int` `vis[N + 1] = { 0 }; ``// mark nodes visited`` ` `    ``dfs(1, leaf, vis, adjacency);`` ` `    ``printLeaf(N, leaf);`` ` `    ``return` `0;``}`

## Java

 `// Java program to print the number of``// leaf nodes of every node``import` `java.util.*;`` ` `class` `GFG``{``static` `Vector> adjacency = ``new``       ``Vector>();`` ` `// Function to insert edges of tree``static` `void` `insert(``int` `x, ``int` `y)``{``    ``adjacency.get(x).add(y);``}`` ` `// Function to run DFS on a tree``static` `void` `dfs(``int` `node, ``int` `leaf[], ``int` `vis[])``{``    ``leaf[node] = ``0``;``    ``vis[node] = ``1``;`` ` `    ``// iterate on all the nodes``    ``// connected to node``    ``for` `(``int` `i = ``0``; i < adjacency.get(node).size(); i++)``    ``{``        ``int` `it = adjacency.get(node).get(i);``         ` `        ``// If not visited``        ``if` `(vis[it] == ``0``) ``        ``{``            ``dfs(it, leaf, vis);``            ``leaf[node] += leaf[it];``        ``}``    ``}`` ` `    ``if` `(adjacency.get(node).size() == ``0``)``        ``leaf[node] = ``1``;``}`` ` `// Function to print number of``// leaf nodes of a node``static` `void` `printLeaf(``int` `n, ``int` `leaf[])``{``    ``// Function to print leaf nodes``    ``for` `(``int` `i = ``1``; i <= n; i++) ``    ``{``        ``System.out.print( ``"The node "` `+ i + ``" has "` `+ ``                          ``leaf[i] + ``" leaf nodes\n"``);``    ``}``}`` ` `// Driver Code``public` `static` `void` `main(String args[])``{``    ``// Given N-ary Tree`` ` `    ``/*     1 ``        ``/ \``        ``2     3``            ``/ | \``            ``4 5 6 */`` ` `    ``int` `N = ``6``; ``// no of nodes``     ` `    ``for``(``int` `i = ``0``; i <= N; i++)``    ``adjacency.add(``new` `Vector());``     ` `    ``insert(``1``, ``2``);``    ``insert(``1``, ``3``);``    ``insert(``3``, ``4``);``    ``insert(``3``, ``5``);``    ``insert(``3``, ``6``);`` ` `    ``// Store count of leaf in subtree of i``    ``int` `leaf[] = ``new` `int``[N + ``1``]; ``     ` `    ``// mark nodes visited``    ``int` `vis[] = ``new` `int``[N + ``1``] ; `` ` `    ``dfs(``1``, leaf, vis);`` ` `    ``printLeaf(N, leaf);``}``}`` ` `// This code is contributed by Arnab Kundu`

## Python3

 `# Python3 program to print the number of``# leaf nodes of every node``adjacency ``=` `[[] ``for` `i ``in` `range``(``100``)]`` ` `# Function to insert edges of tree``def` `insert(x, y):``    ``adjacency[x].append(y)`` ` `# Function to run DFS on a tree``def` `dfs(node, leaf, vis):`` ` `    ``leaf[node] ``=` `0``    ``vis[node] ``=` `1`` ` `    ``# iterate on all the nodes``    ``# connected to node``    ``for` `it ``in` `adjacency[node]:`` ` `        ``# If not visited``        ``if` `(vis[it] ``=``=` `False``):``            ``dfs(it, leaf, vis)``            ``leaf[node] ``+``=` `leaf[it]`` ` `    ``if` `(``len``(adjacency[node]) ``=``=` `0``):``        ``leaf[node] ``=` `1`` ` `# Function to prnumber of``# leaf nodes of a node``def` `printLeaf(n, leaf):``     ` `    ``# Function to prleaf nodes``    ``for` `i ``in` `range``(``1``, n ``+` `1``):``        ``print``(``"The node"``, i, ``"has"``,  ``               ``leaf[i], ``"leaf nodes"``)`` ` `# Driver Code`` ` `# Given N-ary Tree``'''``/*     1``    ``/ \``    ``2     3``        ``/ | \``        ``4 5 6 '''`` ` `N ``=` `6` `# no of nodes``# adjacency list for tree`` ` `insert(``1``, ``2``)``insert(``1``, ``3``)``insert(``3``, ``4``)``insert(``3``, ``5``)``insert(``3``, ``6``)`` ` `# Store count of leaf in subtree of i``leaf ``=` `[``0` `for` `i ``in` `range``(N ``+` `1``)] `` ` `# mark nodes visited``vis ``=` `[``0` `for` `i ``in` `range``(N ``+` `1``)] `` ` `dfs(``1``, leaf, vis)`` ` `printLeaf(N, leaf)`` ` `# This code is contributed by Mohit Kumar`

## C#

 `// C# program to print the number of``// leaf nodes of every node``using` `System;``using` `System.Collections.Generic;`` ` `class` `GFG``{``static` `List> adjacency = ``new``       ``List>();``  ` `// Function to insert edges of tree``static` `void` `insert(``int` `x, ``int` `y)``{``    ``adjacency[x].Add(y);``}``  ` `// Function to run DFS on a tree``static` `void` `dfs(``int` `node, ``int` `[]leaf, ``int` `[]vis)``{``    ``leaf[node] = 0;``    ``vis[node] = 1;``  ` `    ``// iterate on all the nodes``    ``// connected to node``    ``for` `(``int` `i = 0; i < adjacency[node].Count; i++)``    ``{``        ``int` `it = adjacency[node][i];``          ` `        ``// If not visited``        ``if` `(vis[it] == 0) ``        ``{``            ``dfs(it, leaf, vis);``            ``leaf[node] += leaf[it];``        ``}``    ``}``  ` `    ``if` `(adjacency[node].Count == 0)``        ``leaf[node] = 1;``}``  ` `// Function to print number of``// leaf nodes of a node``static` `void` `printLeaf(``int` `n, ``int` `[]leaf)``{``    ``// Function to print leaf nodes``    ``for` `(``int` `i = 1; i <= n; i++) ``    ``{``        ``Console.Write( ``"The node "` `+ i + ``" has "` `+ ``                          ``leaf[i] + ``" leaf nodes\n"``);``    ``}``}``  ` `// Driver Code``public` `static` `void` `Main(String []args)``{``    ``// Given N-ary Tree``  ` `    ``/*     1 ``        ``/ \``        ``2     3``            ``/ | \``            ``4 5 6 */``  ` `    ``int` `N = 6; ``// no of nodes``      ` `    ``for``(``int` `i = 0; i <= N; i++)``    ``adjacency.Add(``new` `List<``int``>());``      ` `    ``insert(1, 2);``    ``insert(1, 3);``    ``insert(3, 4);``    ``insert(3, 5);``    ``insert(3, 6);``  ` `    ``// Store count of leaf in subtree of i``    ``int` `[]leaf = ``new` `int``[N + 1]; ``      ` `    ``// mark nodes visited``    ``int` `[]vis = ``new` `int``[N + 1] ; ``  ` `    ``dfs(1, leaf, vis);``  ` `    ``printLeaf(N, leaf);``}``}`` ` `// This code contributed by Rajput-Ji`
Output:
```The node 1 has 4 leaf nodes
The node 2 has 1 leaf nodes
The node 3 has 3 leaf nodes
The node 4 has 1 leaf nodes
The node 5 has 1 leaf nodes
The node 6 has 1 leaf nodes
```

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live and Geeks Classes Live USA

My Personal Notes arrow_drop_up
{"ft_lang_label":"__label__en","ft_lang_prob":0.674097,"math_prob":0.9486373,"size":6599,"snap":"2021-21-2021-25","text_gpt3_token_len":2151,"char_repetition_ratio":0.18423048,"word_repetition_ratio":0.39517897,"special_character_ratio":0.36838916,"punctuation_ratio":0.14521927,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99841064,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-05-18T21:15:19Z\",\"WARC-Record-ID\":\"<urn:uuid:bbe64050-67c5-407d-ba44-4bf638bbc1bd>\",\"Content-Length\":\"144925\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:418ea0a5-4b80-4050-adfc-98165359cc47>\",\"WARC-Concurrent-To\":\"<urn:uuid:01044115-8730-4fbd-8de9-33bcced095fe>\",\"WARC-IP-Address\":\"204.237.142.187\",\"WARC-Target-URI\":\"https://www.geeksforgeeks.org/number-of-leaf-nodes-in-the-subtree-of-every-node-of-an-n-ary-tree/?ref=rp\",\"WARC-Payload-Digest\":\"sha1:FB4C6NIS5IOSNLBM32NJPVMX4X6K6VQ7\",\"WARC-Block-Digest\":\"sha1:DY5T7O77QZH3JCU73GKILVHUDUV7FJAL\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-21/CC-MAIN-2021-21_segments_1620243991514.63_warc_CC-MAIN-20210518191530-20210518221530-00428.warc.gz\"}"}