Given an N-ary tree, and the weights which are in the form of strings of all the nodes, the task is to count the number of leaf nodes whose weights are palindrome.
Input: 1(ab) / \ (abca)2 5 (aba) / \ (axxa)3 4 (geeks) Output: 2 Explanation: Only the weights of the leaf nodes "axxa" and "aba" are palindromes. Input: 1(abx) / 2(abaa) / 3(amma) Output: 1 Explanation: Only the weight of the leaf node "amma" is palindrome.
Approach: To solve the problem mentioned above follow the steps given below:
- Depth First Search can be used to traverse the complete tree.
- We will keep track of parent while traversing to avoid the visited node array.
- Initially for every node we can set a flag and if the node have at least one child (i.e. non-leaf node) then we will reset the flag.
- The nodes with no children are the leaf nodes. For every leaf node, we will check if it’s string is palindrome or not. If yes then increment the count.
Below is the implementation of the above approach:
- Count the nodes of the given tree whose weighted string is a palindrome
- Count the nodes of the tree whose weighted string contains a vowel
- Count the nodes of a tree whose weighted string does not contain any duplicate characters
- Count the nodes of a tree whose weighted string is an anagram of the given string
- Count of root to leaf paths whose permutation is palindrome in a Binary Tree
- Count Non-Leaf nodes in a Binary Tree
- Determine the count of Leaf nodes in an N-ary tree
- Program to count leaf nodes in a binary tree
- Iterative program to count leaf nodes in a Binary Tree
- Minimum difference between any two weighted nodes in Sum Tree of the given Tree
- Minimum distance to visit all the nodes of an undirected weighted tree
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Queries to find sum of distance of a given node to every leaf node in a Weighted Tree
- Maximum weighted edge in path between two nodes in an N-ary tree using binary lifting
- Remove all leaf nodes from a Generic Tree or N-ary Tree
- Print all leaf nodes of an n-ary tree using DFS
- Sum of all leaf nodes of binary tree
- Product of all leaf nodes of binary tree
- Print all leaf nodes of a binary tree from right to left
- Number of leaf nodes in the subtree of every node of an n-ary tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.
Improved By : Amal Kumar Choubey