Given a N-ary tree represented as adjacency list, we need to write a program to count all such nodes in this tree which has more number of children than its parent.
In the above tree, the count will be 1 as there is only one such node which is ‘2’ which has more number of children than its parent. 2 has three children (4, 5 and 6) whereas its parent, 1 has only two children (2 and 3).
We can solve this problem using both BFS and DFS algorithms. We will explain here in details about how to solve this problem using BFS algorithm.
As the tree is represented using adjacency list representation. So, for any node say ‘u’ the number of children of this node can be given as adj[u].size().
Now the idea is to apply BFS on the given tree and while traversing the children of a node ‘u’ say ‘v’ we will simply check is adj[v].size() > adj[u].size().
Below is the implementation of above idea:
Time Complexity: O( n ) , where n is the number of nodes in the tree.
This article is contributed by Harsh Agarwal. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
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.
- General Tree (Each node can have arbitrary number of children) Level Order Traversal
- Minimum number of Nodes to be removed such that no subtree has more than K nodes
- Count nodes with two children at level L in a Binary Tree
- Count of nodes in a Binary tree with immediate children as its factors
- Count of nodes in a Binary Tree whose immediate children are co-prime
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Count of Nodes whose both immediate children are its prime factors
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
- Check which player visits more number of Nodes
- Number of children of given node in n-ary Tree
- Count of all prime weight nodes between given nodes in the given Tree
- Find root of the tree where children id sum for every node is given
- Find the number of distinct pairs of vertices which have a distance of exactly k in a tree
- Check for Children Sum Property in a Binary Tree
- Node having maximum sum of immediate children and itself in n-ary tree
- Maximum parent children sum in Binary tree
- Iterative approach to check for children sum property in a Binary Tree
- Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree
- Number of nodes greater than a given value in n-ary tree
- Count of Nodes which has Prime Digit sum weight in a Tree