Average width in a N-ary tree
Given a Generic Tree consisting of N nodes, the task is to find the average width for each node present in the given tree.
The average width for each node can be calculated by the ratio of the total number of nodes in that subtree(including the node itself) to the total number of levels under that node.
/ \ / \ \
4 5 6 7 8
Output: 1:2, 2:1, 3:2, 4:1, 5:1, 6:1, 7:1, 8:1
Explanation: The average width for each node can be calculated as
For node 1: 8/3 = 2
For node 2: 3/2 = 1
For node 3: 4/2 = 2
For node 4: 1/1 = 1
For node 5: 1/1 = 1
For node 6: 1/1 = 1
For node 7: 1/1 = 1
For node 8: 1/1 = 1
Approach: The average width can be calculated by finding the subtree size of each node in the N-ary tree and the level or height of each node in the N-ary tree. Both can be calculated using a single DFS traversal.
Below is the implementation of the above approach:
4:1, 6:1, 2:1, 5:1, 7:1, 8:1, 3:2, 1:2,
Time Complexity: O(N)
Auxiliary Space: O(N)
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.