Given an N-ary tree, print the number of leaf nodes in the subtree of every node.
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
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:
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
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
- Queries to find sum of distance of a given node to every leaf node in a Weighted Tree
- Implementing a BST where every node stores the maximum number of nodes in the path till any leaf
- Minimum number of Nodes to be removed such that no subtree has more than K nodes
- Node having maximum number of nodes less than its value in its subtree
- Check if two nodes are in same subtree of the root node
- Queries to find the Minimum Weight from a Subtree of atmost D-distant Nodes from Node X
- Print the longest leaf to leaf path in a Binary tree
- Subtree of all nodes in a tree using DFS
- Print the nodes of binary tree as they become the leaf node
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Remove all leaf nodes from a Generic Tree or N-ary Tree
- Find the Kth node in the DFS traversal of a given subtree in a Tree
- Find GCD of each subtree of a given node in an N-ary Tree for Q queries
- Check if a binary tree is subtree of another binary tree | Set 1
- Check if a binary tree is subtree of another binary tree | Set 2
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Count of nodes having odd divisors in the given subtree for Q queries
- Print all nodes that are at distance k from a leaf node
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.