The Wayback Machine - https://web.archive.org/web/20240817223722/https://www.geeksforgeeks.org/average-width-in-a-n-ary-tree/
Open In App

Average width in a N-ary tree

Last Updated : 16 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Examples:

Input:
              1
           /    \
        2        3
     /  \     /  \  \
  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:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
vector<vector<int> > ans;
 
// Node structure
struct Node {
    int val;
    vector<Node*> child;
};
 
// Utility function to create a new
// tree node
Node* newNode(int key)
{
    Node* temp = new Node;
    temp->val = key;
    return temp;
}
 
// Function to find levels and
// subtree sizes
vector<int> UtilityFun(Node* root, vector<vector<int> >& ans)
{
    if (root == nullptr)
        return { 0, 0 };
 
    // Num nodes and level with just
    // a single node
    int totalNodes = 1, totalLevels = 1;
 
    // Recur for all children
    for (int i = 0; i < root->child.size(); i++) {
        vector<int> info = UtilityFun(root->child[i], ans);
        totalNodes += info[0];
        totalLevels = max(totalLevels, 1 + info[1]);
    }
 
    // Finding the current Width
    int currentAverageWidth = totalNodes / totalLevels;
 
    // Storing in ans
    ans.push_back({ root->val, currentAverageWidth });
 
    return { totalNodes, totalLevels };
}
 
// Function to find the average width
// of all nodes
vector<vector<int> > findAvgWidth(Node* root)
{
    if (root == nullptr)
        return {};
 
    // Function Call
    UtilityFun(root, ans);
    return ans;
}
 
// Function to display the values
void display(vector<vector<int> > ans)
{
    for (int i = 0; i < ans.size(); i++) {
        cout << ans[i][0] << ":" << ans[i][1] << ", ";
    }
}
 
// Driver Code
int main()
{
    // Given Input
    Node* root = newNode(1);
    (root->child).push_back(newNode(2));
    (root->child).push_back(newNode(3));
    (root->child[0]->child).push_back(newNode(4));
    (root->child[1]->child).push_back(newNode(5));
    (root->child[0]->child).push_back(newNode(6));
    (root->child[1])->child.push_back(newNode(7));
    (root->child[1]->child).push_back(newNode(8));
 
    // Function Call
    findAvgWidth(root);
 
    // Function Call
    display(ans);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
public class Main
{
    static Vector<Vector<Integer>> ans = new Vector<Vector<Integer>>();
     
    // Node structure
    static class Node {
         
        public int val;
        public Vector<Node> child;
         
        public Node(int key)
        {
            val = key;
            child = new Vector<Node>();
        }
    }
     
    // Utility function to create a new
    // tree node
    static Node newNode(int key)
    {
        Node temp = new Node(key);
        return temp;
    }
   
    // Function to find levels and
    // subtree sizes
    static Vector<Integer> UtilityFun(Node root, Vector<Vector<Integer>> ans)
    {
        if (root == null)
        {
            Vector<Integer> temp = new Vector<Integer>();
            temp.add(0);
            temp.add(0);
            return temp;
        }
   
        // Num nodes and level with just
        // a single node
        int totalNodes = 1, totalLevels = 1;
   
        // Recur for all children
        for (int i = 0; i < root.child.size(); i++) {
            Vector<Integer> info = UtilityFun(root.child.get(i), ans);
            totalNodes += info.get(0);
            totalLevels = Math.max(totalLevels, 1 + info.get(1));
        }
   
        // Finding the current Width
        int currentAverageWidth = totalNodes / totalLevels;
   
        // Storing in ans
        Vector<Integer> temp = new Vector<Integer>();
        temp.add(root.val);
        temp.add(currentAverageWidth);
        ans.add(temp);
         
        temp = new Vector<Integer>();
        temp.add(totalNodes);
        temp.add(totalLevels);
   
        return temp;
    }
   
    // Function to find the average width
    // of all nodes
    static Vector<Vector<Integer>> findAvgWidth(Node root)
    {
        if (root == null)
            return new Vector<Vector<Integer>>();
   
        // Function Call
        UtilityFun(root, ans);
        return ans;
    }
   
    // Function to display the values
    static void display(Vector<Vector<Integer>> ans)
    {
        for (int i = 0; i < ans.size(); i++) {
            System.out.print(ans.get(i).get(0) + ":" + ans.get(i).get(1) + ", ");
        }
    }
     
    public static void main(String[] args)
    {
        // Given Input
        Node root = newNode(1);
        (root.child).add(newNode(2));
        (root.child).add(newNode(3));
        (root.child.get(0).child).add(newNode(4));
        (root.child.get(1).child).add(newNode(5));
        (root.child.get(0).child).add(newNode(6));
        (root.child.get(1)).child.add(newNode(7));
        (root.child.get(1).child).add(newNode(8));
         
        // Function Call
        findAvgWidth(root);
         
        // Function Call
        display(ans);
    }
}
 
// This code is contributed by suresh07.


Python3




# Python3 program for the above approach
ans = []
 
# Node structure
class Node:
    def __init__(self, key):
        self.val = key
        self.child = []
 
# Utility function to create a new
# tree node
def newNode(key):
    temp = Node(key)
    return temp
 
# Function to find levels and
# subtree sizes
def UtilityFun(root, ans):
    if (root == None):
        return [ 0, 0 ]
 
    # Num nodes and level with just
    # a single node
    totalNodes, totalLevels = 1, 1
 
    # Recur for all children
    for i in range(len(root.child)):
        info = UtilityFun(root.child[i], ans)
        totalNodes += info[0]
        totalLevels = max(totalLevels, 1 + info[1])
 
    # Finding the current Width
    currentAverageWidth = int(totalNodes / totalLevels)
 
    # Storing in ans
    ans.append([ root.val, currentAverageWidth ])
 
    return [ totalNodes, totalLevels ]
 
# Function to find the average width
# of all nodes
def findAvgWidth(root):
    if (root == None):
        return []
 
    # Function Call
    UtilityFun(root, ans)
    return ans
 
# Function to display the values
def display(ans):
    for i in range(len(ans)):
        print(ans[i][0], ":", ans[i][1], ", ", sep="",end="")
 
# Given Input
root = newNode(1)
(root.child).append(newNode(2))
(root.child).append(newNode(3))
(root.child[0].child).append(newNode(4))
(root.child[1].child).append(newNode(5))
(root.child[0].child).append(newNode(6))
(root.child[1]).child.append(newNode(7))
(root.child[1].child).append(newNode(8))
 
# Function Call
findAvgWidth(root)
 
# Function Call
display(ans)
 
# This code is contributed by divyesh072019.


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG {
     
    static List<List<int>> ans = new List<List<int>>();
     
    // Node structure
    class Node {
        
        public int val;
        public List<Node> child;
        
        public Node(int key)
        {
            val = key;
            child = new List<Node>();
        }
    }
     
    // Utility function to create a new
    // tree node
    static Node newNode(int key)
    {
        Node temp = new Node(key);
        return temp;
    }
  
    // Function to find levels and
    // subtree sizes
    static List<int> UtilityFun(Node root, List<List<int>> ans)
    {
        if (root == null)
        {
            List<int> temp = new List<int>();
            temp.Add(0);
            temp.Add(0);
            return temp;
        }
  
        // Num nodes and level with just
        // a single node
        int totalNodes = 1, totalLevels = 1;
  
        // Recur for all children
        for (int i = 0; i < root.child.Count; i++) {
            List<int> info = UtilityFun(root.child[i], ans);
            totalNodes += info[0];
            totalLevels = Math.Max(totalLevels, 1 + info[1]);
        }
  
        // Finding the current Width
        int currentAverageWidth = totalNodes / totalLevels;
  
        // Storing in ans
        ans.Add(new List<int>{root.val, currentAverageWidth});
  
        return new List<int>{totalNodes, totalLevels};
    }
  
    // Function to find the average width
    // of all nodes
    static List<List<int>> findAvgWidth(Node root)
    {
        if (root == null)
            return new List<List<int>>();
  
        // Function Call
        UtilityFun(root, ans);
        return ans;
    }
  
    // Function to display the values
    static void display(List<List<int>> ans)
    {
        for (int i = 0; i < ans.Count; i++) {
            Console.Write(ans[i][0] + ":" + ans[i][1] + ", ");
        }
    }
     
  static void Main()
  {
     
    // Given Input
    Node root = newNode(1);
    (root.child).Add(newNode(2));
    (root.child).Add(newNode(3));
    (root.child[0].child).Add(newNode(4));
    (root.child[1].child).Add(newNode(5));
    (root.child[0].child).Add(newNode(6));
    (root.child[1]).child.Add(newNode(7));
    (root.child[1].child).Add(newNode(8));
    
    // Function Call
    findAvgWidth(root);
    
    // Function Call
    display(ans);
  }
}
 
// This code is contributed by mukesh07.


Javascript




<script>
    // Javascript program for the above approach 
     
    let ans = []
     
    // Node structure
    class Node
    {
        constructor(key) {
           this.child = [];
           this.val = key;
        }
    }
     
    // Utility function to create a new
    // tree node
    function newNode(key)
    {
        let temp = new Node(key);
        return temp;
    }
 
    // Function to find levels and
    // subtree sizes
    function UtilityFun(root, ans)
    {
        if (root == null)
            return [ 0, 0 ];
 
        // Num nodes and level with just
        // a single node
        let totalNodes = 1, totalLevels = 1;
 
        // Recur for all children
        for (let i = 0; i < root.child.length; i++) {
            let info = UtilityFun(root.child[i], ans);
            totalNodes += info[0];
            totalLevels = Math.max(totalLevels, 1 + info[1]);
        }
 
        // Finding the current Width
        let currentAverageWidth = parseInt(totalNodes / totalLevels, 10);
 
        // Storing in ans
        ans.push([ root.val, currentAverageWidth ]);
 
        return [ totalNodes, totalLevels ];
    }
 
    // Function to find the average width
    // of all nodes
    function findAvgWidth(root)
    {
        if (root == null)
            return [];
 
        // Function Call
        UtilityFun(root, ans);
        return ans;
    }
 
    // Function to display the values
    function display(ans)
    {
        for (let i = 0; i < ans.length; i++) {
            document.write(ans[i][0] + ":" + ans[i][1] + ", ");
        }
    }
     
    // Given Input
    let root = newNode(1);
    (root.child).push(newNode(2));
    (root.child).push(newNode(3));
    (root.child[0].child).push(newNode(4));
    (root.child[1].child).push(newNode(5));
    (root.child[0].child).push(newNode(6));
    (root.child[1]).child.push(newNode(7));
    (root.child[1].child).push(newNode(8));
   
    // Function Call
    findAvgWidth(root);
   
    // Function Call
    display(ans);
 
// This code is contributed by rameshtravel07.
</script>


 
 

Output

4:1, 6:1, 2:1, 5:1, 7:1, 8:1, 3:2, 1:2, 

 

Time Complexity: O(N)
Auxiliary Space: O(N)

 



Previous Article
Next Article

Similar Reads

Maximum width of an N-ary tree
Given an N-ary tree, the task is to find the maximum width of the given tree. The maximum width of a tree is the maximum of width among all levels. Examples: Input: 4 / | \ 2 3 -5 / \ /\ -1 3 -2 6 Output: 4 Explanation: Width of 0th level is 1. Width of 1st level is 3. Width of 2nd level is 4. Therefore, the maximum width is 4 Input: 1 / | \ 2 -1 3
9 min read
Build a segment tree for N-ary rooted tree
Prerequisite: Segment tree and depth first search.In this article, an approach to convert an N-ary rooted tree( a tree with more than 2 children) into a segment tree is discussed which is used to perform a range update queries. Why do we need a segment tree when we already have an n-ary rooted tree? Many times, a situation occurs where the same ope
15+ min read
Check if the given n-ary tree is a binary tree
Given an n-ary tree, the task is to check whether the given tree is binary or not. Examples: Input: A / \ B C / \ \ D E F Output: Yes Input: A / | \ B C D \ F Output: No Approach: Every node in a binary tree can have at most 2 children. So, for every node of the given tree, count the number of children and if for any node the count exceeds 2 then p
6 min read
Remove all leaf nodes from a Generic Tree or N-ary Tree
Given a Generic tree, the task is to delete the leaf nodes from the tree. Examples: Input: 5 / / \ \ 1 2 3 8 / / \ \ 15 4 5 6 Output: 5 : 1 2 3 1 : 2 : 3 : Explanation: Deleted leafs are: 8, 15, 4, 5, 6 Input: 8 / | \ 9 7 2 / | \ | / / | \ \ 4 5 6 10 11 1 2 2 3 Output: 8: 9 7 2 9: 7: 2: Approach: Follow the steps given below to solve the problem Co
9 min read
Count of nodes in given N-ary tree such that their subtree is a Binary Tree
Given an N-ary tree root, the task is to find the count of nodes such that their subtree is a binary tree. Example: Input: Tree in the image below Output: 11Explanation: The nodes such that there subtree is a binary tree are {2, 8, 10, 6, 7, 3, 1, 9, 5, 11, 12}. Input: Tree in the image below Output: 9 Approach: The given problem can be solved by u
11 min read
Tree of Space - Locking and Unlocking N-Ary Tree
Given a world map in the form of Generic M-ary Tree consisting of N nodes and an array queries[], the task is to implement the functions Lock, Unlock and Upgrade for the given tree. For each query in queries[], the functions return true when the operation is performed successfully, otherwise it returns false. The functions are defined as: X: Name o
10 min read
What is Generic Tree or N-ary Tree?
Generic tree or an N-ary tree is a versatile data structure used to organize data hierarchically. Unlike binary trees that have at most two children per node, generic trees can have any number of child nodes. This flexibility makes them suitable for representing hierarchical data where each node can have several branches or children. What is a Gene
4 min read
Mirror of n-ary Tree
Given a Tree where every node contains variable number of children, convert the tree to its mirror. Below diagram shows an example. We strongly recommend you to minimize your browser and try this yourself first. Node of tree is represented as a key and a variable sized array of children pointers. The idea is similar to mirror of Binary Tree. For ev
9 min read
Even size subtree in n-ary tree
Given an n-ary tree of n vertices and n-1 edges. The tree is given in the form of adjacency list. Find number of subtrees of even size in given tree. Examples: Input : 1 / \ 2 3 / \ \ 4 5 6 / \ 7 8 Output : 2 Subtree rooted at 1 and 3 are of even size. Input : 1 / \ 2 3 / | \ \ 4 5 6 7 / | \ 8 9 10 Output : 3 Subtree rooted at 1, 3 and 5 are of eve
7 min read
Diameter of n-ary tree using BFS
N-ary tree refers to the rooted tree in which each node having atmost k child nodes. The diameter of n-ary tree is the longest path between two leaf nodes. Various approaches have already been discussed to compute diameter of tree. Diameter of an N-ary tree Diameter of a Binary Tree in O(n) Diameter of a Binary Tree Diameter of a tree using DFS Thi
7 min read
Sum of all elements of N-ary Tree
Given an N-ary tree, find sum of all elements in it. Example : Input : Above tree Output : Sum is 536 Approach : The approach used is similar to Level Order traversal in a binary tree. Start by pushing the root node in the queue. And for each node, while popping it from queue, add the value of this node in the sum variable and push the children of
6 min read
Immediate Smaller element in an N-ary Tree
Given an element x, task is to find the value of its immediate smaller element. Example : Input : x = 30 (for above tree) Output : Immediate smaller element is 25 Explanation : Elements 2, 15, 20 and 25 are smaller than x i.e, 30, but 25 is the immediate smaller element and hence the answer. Approach : Let res be the resultant node.Initialize the r
7 min read
Number of siblings of a given Node in n-ary Tree
Given an N-ary tree, find the number of siblings of given node x. Assume that x exists in the given n-ary tree. Example : Input : 30 Output : 3 Approach: For every node in the given n-ary tree, push the children of the current node in the queue. While adding the children of current node in queue, check if any children is equal to the given value x
13 min read
Number of children of given node in n-ary Tree
Given a node x, find the number of children of x(if it exists) in the given n-ary tree. Example : Input : x = 50 Output : 3 Explanation : 50 has 3 children having values 40, 100 and 20. Approach : Initialize the number of children as 0.For every node in the n-ary tree, check if its value is equal to x or not. If yes, then return the number of child
7 min read
Preorder Traversal of N-ary Tree Without Recursion
Given an n-ary tree, print preorder traversal of it. Example : Preorder traversal of below tree is A B K N M J F D G E C H I L The idea is to use stack like iterative preorder traversal of binary tree. Create an empty stack to store nodes. Push the root node to the stack. Run a loop while the stack is not empty Pop the top node from stack. Print th
7 min read
Number of leaf nodes in the subtree of every node of an n-ary tree
Given an N-ary tree, print the number of leaf nodes in the subtree of every node. Examples: 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
8 min read
Level with maximum number of nodes using DFS in a N-ary tree
Given a N-ary tree, the task is to print the level with the maximum number of nodes. Examples: Input : For example, consider the following tree 1 - Level 1 / \ 2 3 - Level 2 / \ \ 4 5 6 - Level 3 / \ / 7 8 9 - Level 4 Output : Level-3 and Level-4 Approach: Insert all the connecting nodes to a 2-D vector tree.Run a DFS on the tree such that height[n
10 min read
Number of Paths of Weight W in a K-ary tree
Given a K-ary tree, where each node is having K children and each edge has some weight. All the edges i.e. K, that goes from a particular node to all its children have weights in ascending order 1, 2, 3, ..., K. Find the number of paths having total weight as W (sum of all edge weights in the path) starting from root and containing atleast one edge
7 min read
DP on Trees | Set-3 ( Diameter of N-ary Tree )
Given an N-ary tree T of N nodes, the task is to calculate the longest path between any two nodes(also known as the diameter of the tree). Example 1: Example 2: Different approaches to solving these problems have already been discussed: https://www.geeksforgeeks.org/diameter-n-ary-tree/https://www.geeksforgeeks.org/diameter-n-ary-tree-using-bfs/ In
9 min read
Number of special nodes in an n-ary tree
Given an n-ary tree rooted at vertex 1. The tree has n vertices and n-1 edges. Each node has a value associated with it and tree is input in the form of adjacency list. The task is to find the number of special nodes in the tree. A node is special if the path from the root to the node consists of distinct value nodes.Examples: Input: val[] = {1, 2,
6 min read
GCD from root to leaf path in an N-ary tree
Given an N-ary tree and an array val[] which stores the values associated with all the nodes. Also given are a leaf node X and N integers which denotes the value of the node. The task is to find the gcd of all the numbers in the node in the path between leaf to the root. Examples: Input: 1 / \ 2 3 / / \ 4 5 6 / \ 7 8 val[] = { -1, 6, 2, 6, 3, 4, 12
7 min read
Check if given Generic N-ary Tree is Symmetric horizontally
Given an N-ary tree root, the task is to check if it is symmetric horizontally (Mirror image of itself). Example: Input: root = 7 / / \ \ 4 2 2 4 / | / | | \ | \ 3 2 6 7 7 6 2 3Output: trueExplanation: The left side of the tree is a mirror image of the right side Input: root= 2 / | \ 3 4 3 / | \ 5 6 5Output: true Approach: The given problem can be
8 min read
Construct a Complete N-ary Tree from given Postorder Traversal
Given an array arr[] of size M that contains the post-order traversal of a complete N-ary tree, the task is to generate the N-ary tree and print its preorder traversal. A complete tree is a tree where all the levels of the tree are completely filled, except may be for the last level but the nodes in the last level are as left as possible. Examples:
13 min read
Node whose removal minimizes the maximum size forest from an N-ary Tree
Given an n-ary tree T, the task is to find a node whose removal minimizes the maximum size of all forests(connected components) generated. Examples: Input: 1 / | \ 2 3 4 / \ 5 6Output: 1Explanation:There are six nodes which can be removed to form forests:Remove(1): Largest Forest size is 3Remove(2): Largest Forest size is 3Remove(3): Largest Forest
7 min read
Insertion in n-ary tree in given order and Level order traversal
Given a set of parent nodes where the index of the array is the child of each Node value, the task is to insert the nodes as a forest(multiple trees combined together) where each parent could have more than two children. After inserting the nodes, print each level in a sorted format. Example: Input: arr[] = {5, 3, -1, 2, 5, 3} Output:-1 231 5Input:
10 min read
Kth ancestor of a node in an N-ary tree using Binary Lifting Technique
Given a vertex V of an N-ary tree and an integer K, the task is to print the Kth ancestor of the given vertex in the tree. If there does not exist any such ancestor then print -1.Examples: Input: K = 2, V = 4 Output: 1 2nd parent of vertex 4 is 1.Input: K = 3, V = 4 Output: -1 Approach: The idea is to use Binary Lifting Technique. This technique is
9 min read
Minimum valued node having maximum depth in an N-ary Tree
Given a tree of N nodes, the task is to find the node having maximum depth starting from the root node, taking the root node at zero depth. If there are more than 1 maximum depth node, then find the one having the smallest value. Examples: Input: 1 / \ 2 3 / \ 4 5 Output: 4 Explanation: For this tree: Height of Node 1 - 0, Height of Node 2 - 1, Hei
5 min read
Maximum weighted edge in path between two nodes in an N-ary tree using binary lifting
Given an N-ary tree with weighted edge and Q queries where each query contains two nodes of the tree. The task is to find the maximum weighted edge in the simple path between these two nodes.Examples: Naive Approach: A simple solution is to traverse the whole tree for each query and find the path between the two nodes.Efficient Approach: The idea i
15 min read
Count of subtrees from an N-ary tree consisting of single colored nodes
Given a N-ary tree consisting of N nodes and a matrix edges[][] consisting of N - 1 edges of the form (X, Y) denoting the edge between node X and node Y and an array col[] consisting of values: 0: Uncolored node.1: Node colored red.2: Node colored blue. The task is to find the number of subtrees of the given tree which consists of only single-color
13 min read
Find GCD of each subtree of a given node in an N-ary Tree for Q queries
Given an N-ary Tree containing N nodes, values associated with each node and Q queries, where each query contains a single node. The task is to find the GCD of values of all the nodes present in the subtree (including itself). Example: Tree: 1(2) / \ / \ 2(3) 3(4) / \ / \ 4(8) 5(16) query[]: {2, 3, 1} Output: {3, 4, 1} Explanation: For query 1: GCD
10 min read
three90RightbarBannerImg