📌  相关文章
📜  计算树的每个级别中某个级别中存在的所有节点的总和

📅  最后修改于: 2021-04-17 15:51:56             🧑  作者: Mango

给定一个由N个节点(以0为根)组成的通用树,其中每个节点都与一个值相关联,该树的每个级别的任务是查找该树的该级别上存在的所有节点值的总和。

例子:

方法:请按照以下步骤解决问题:

  1. 使用DFS或BFS遍历树
  2. 使用此方法存储此节点的级别。
  3. 然后,将节点值添加到数组中节点的相应级别,例如sum []。
  4. 打印数组sum [],显示每个级别上所有节点的总和。

下面是上述方法的实现:

C++
// C++ implementation of
// the above approach
#include 
using namespace std;
 
// Function to add edges to the tree
void add_edge(int a, int b,
              vector >& tree)
{
    // 0-based indexing
    a--, b--;
 
    tree[a].push_back(b);
    tree[b].push_back(a);
}
 
// Function to print sum of
// nodes on all levels of a tree
void dfs(int u, int level, int par,
         int node_values[], vector >& tree,
         map& sum, int& depth)
{
    // update max depth of tree
    depth = max(depth, level);
 
    // Add value of current node
    // to its corresponding level
    sum[level] += node_values[u];
 
    for (int child : tree[u]) {
 
        if (child == par)
            continue;
 
        // Recursive traverse child nodes
        dfs(child, level + 1, u, node_values,
            tree, sum, depth);
    }
}
 
// Function to calculate sum of
// nodes of each level of the Tree
void getSum(int node_values[],
            vector >& tree)
{
    // Depth of the tree
    int depth = 0;
 
    // Stores sum at each level
    map sum;
 
    dfs(0, 0,
        -1, node_values,
        tree, sum, depth);
 
    // Print final sum
    for (int i = 0; i <= depth; i++) {
        cout << "Sum of level " << i
             << " = " << sum[i] << endl;
    }
}
 
// Driver Code
int32_t main()
{
 
    // Create a tree structure
    int N = 10;
 
    vector > tree(N);
    add_edge(1, 2, tree);
    add_edge(1, 3, tree);
    add_edge(2, 4, tree);
    add_edge(3, 5, tree);
    add_edge(3, 8, tree);
    add_edge(5, 6, tree);
    add_edge(5, 7, tree);
    add_edge(8, 9, tree);
    add_edge(8, 10, tree);
 
    int node_values[]
        = { 2, 3, 4, 4, 7,
            6, 2, 3, 9, 1 };
 
    // Function call to get the sum
    // of nodes of different level
    getSum(node_values, tree);
 
    return 0;
}


Java
// Java implementation of
// the above approach
import java.io.*;
import java.util.*;
 
class GFG{
     
static Map sum = new HashMap<>();
static int depth = 0;
 
// Function to add edges to the tree
static void add_edge(int a, int b,
                     ArrayList> tree)
{
     
    // 0-based indexing
    a--;
    b--;
  
    tree.get(a).add(b);
    tree.get(b).add(a);
}
  
// Function to print sum of
// Nodes on all levels of a tree
static void dfs(int u, int level, int par,
                int []node_values,
                ArrayList> tree)
{
     
    // Update max depth of tree
    depth = Math.max(depth, level);
  
    // Add value of current node
    // to its corresponding level
    if (sum.containsKey(level))
    {
        sum.put(level, sum.get(level) +
                       node_values[u]);
    }
    else
        sum.put(level,node_values[u]);
       
    for(int child : tree.get(u))
    {
        if (child == par)
            continue;
  
        // Recursive traverse child nodes
        dfs(child, level + 1, u, node_values,
            tree);
    }
}
  
// Function to calculate sum of
// nodes of each level of the Tree
static void getSum(int []node_values,
                   ArrayList> tree)
{
  
    dfs(0, 0, -1, node_values, tree);
  
    // Print final sum
    for(int i = 0; i <= depth; i++)
    {
        System.out.println("Sum of level " + (int) i +
                                     " = " + sum.get(i));
    }
}
  
// Driver Code
public static void main (String[] args)
{
     
    // Create a tree structure
    int N = 10;
  
    ArrayList> tree = new ArrayList>();
    for(int i = 0; i < N; i++)
       tree.add(new ArrayList());
        
    add_edge(1, 2, tree);
    add_edge(1, 3, tree);
    add_edge(2, 4, tree);
    add_edge(3, 5, tree);
    add_edge(3, 8, tree);
    add_edge(5, 6, tree);
    add_edge(5, 7, tree);
    add_edge(8, 9, tree);
    add_edge(8, 10, tree);
  
    int []node_values = { 2, 3, 4, 4, 7,
                          6, 2, 3, 9, 1 };
  
    // Function call to get the sum
    // of nodes of different level
    getSum(node_values, tree);
}
}
 
// This code is contributed by avanitrachhadiya2155


Python3
# Python3 implementation of
# the above approach
 
# Function to add edges to the tree
def add_edge(a, b):
    global tree
     
    # 0-based indexing
    a, b = a - 1, b - 1
    tree[a].append(b)
    tree[b].append(a)
 
# Function to prsum of
# nodes on all levels of a tree
def dfs(u, level, par, node_values):
    global sum, tree, depth
     
    # update max depth of tree
    depth = max(depth, level)
 
    # Add value of current node
    # to its corresponding level
    sum[level] = sum.get(level, 0) + node_values[u]
    for child in tree[u]:
        if (child == par):
            continue
 
        # Recursive traverse child nodes
        dfs(child, level + 1, u, node_values)
 
# Function to calculate sum of
# nodes of each level of the Tree
def getSum(node_values):
    global sum, depth, tree
     
    # Depth of the tree
    # depth = 0
 
    # Stores sum at each level
    # map sum
    dfs(0, 0, -1, node_values)
 
    # Prfinal sum
    for i in range(depth + 1):
        print("Sum of level", i, "=", sum[i])
 
# Driver Code
if __name__ == '__main__':
 
    # Create a tree structure
    N = 10
    tree = [[] for i in range(N+1)]
    sum = {}
    depth = 0
    add_edge(1, 2)
    add_edge(1, 3)
    add_edge(2, 4)
    add_edge(3, 5)
    add_edge(3, 8)
    add_edge(5, 6)
    add_edge(5, 7)
    add_edge(8, 9)
    add_edge(8, 10)
    node_values = [2, 3, 4, 4, 7, 6, 2, 3, 9, 1]
 
    # Function call to get the sum
    # of nodes of different level
    getSum(node_values)
 
    # This code is contributed by mohit kumar 29.


C#
// C# implementation of
// the above approach
using System;
using System.Collections.Generic;
class GFG
{
  
static Dictionary sum = new Dictionary();
  static int depth = 0;
   
// Function to add edges to the tree
static void add_edge(int a, int b, List> tree)
{
   
    // 0-based indexing
    a--;
    b--;
 
    tree[a].Add(b);
    tree[b].Add(a);
}
 
// Function to print sum of
// Nodes on all levels of a tree
static void dfs(int u, int level, int par,
         int []node_values, List> tree
         )
{
   
    // update max depth of tree
    depth = Math.Max(depth, level);
 
    // Add value of current node
    // to its corresponding level
    if(sum.ContainsKey(level))
      sum[level] += node_values[u];
    else
      sum[level] = node_values[u];
 
    foreach (int child in tree[u]) {
 
        if (child == par)
            continue;
 
        // Recursive traverse child nodes
        dfs(child, level + 1, u, node_values,
            tree);
    }
}
 
// Function to calculate sum of
// nodes of each level of the Tree
static void getSum(int []node_values, List> tree)
{
 
    dfs(0, 0, -1, node_values, tree);
 
    // Print final sum
    for (int i = 0; i <= depth; i++) {
        Console.WriteLine("Sum of level " + (int) i + " = "+ sum[i]);
    }
}
 
// Driver Code
public static void Main()
{
 
    // Create a tree structure
    int N = 10;
 
    List > tree = new List>();
    for(int i = 0; i < N; i++)
       tree.Add(new List());
    add_edge(1, 2, tree);
    add_edge(1, 3, tree);
    add_edge(2, 4, tree);
    add_edge(3, 5, tree);
    add_edge(3, 8, tree);
    add_edge(5, 6, tree);
    add_edge(5, 7, tree);
    add_edge(8, 9, tree);
    add_edge(8, 10, tree);
 
    int []node_values = {2, 3, 4, 4, 7,6, 2, 3, 9, 1};
 
    // Function call to get the sum
    // of nodes of different level
    getSum(node_values, tree);
}
}
 
// This code is contributed by bgangwar59.


输出:
Sum of level 0 = 2
Sum of level 1 = 7
Sum of level 2 = 14
Sum of level 3 = 18

时间复杂度: O(N)
辅助空间: O(N)