For a binary tree with n nodes, how many nodes are there which has got both a parent and a child
Answers
Explanation:
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.
For Example,
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).
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
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().