📜  N-ary Tree 中的最大级别总和

📅  最后修改于: 2021-09-06 05:30:31             🧑  作者: Mango

给定一个由值为[1, N]的节点和一个数组value[]组成的N 元树,其中每个节点ivalue[i]相关联,任务是找到所有级别的所有节点值之和的最大值N 叉树

例子:

方法:这个问题可以使用Level order Traversal来解决。在进行遍历时,分别处理不同层次的节点。对于正在处理的每个级别,计算该级别的节点总和并跟踪最大总和。按照步骤:

  1. 将当前级别的所有子节点存储到队列中,然后在特定级别的级别顺序遍历完成后计算当前级别的节点总和。
  2. 由于队列现在包含下一层的所有节点,因此可以通过遍历队列轻松计算下一层的节点总数。
  3. 对连续级别执行相同的过程并更新在每个级别找到的最大节点总和。
  4. 完成上述步骤后,打印存储的值的最大总和。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the maximum sum
// a level in N-ary treeusing BFS
int maxLevelSum(int N, int M,
                vector Value,
                int Edges[][2])
{
    // Stores the edges of the graph
    vector adj[N];
 
    // Create Adjacency list
    for (int i = 0; i < M; i++) {
        adj[Edges[i][0]].push_back(
            Edges[i][1]);
    }
 
    // Initialize result
    int result = Value[0];
 
    // Stores the nodes of each level
    queue q;
 
    // Insert root
    q.push(0);
 
    // Perform level order traversal
    while (!q.empty()) {
 
        // Count of nodes of the
        // current level
        int count = q.size();
 
        int sum = 0;
 
        // Traverse the current level
        while (count--) {
 
            // Dequeue a node from queue
            int temp = q.front();
            q.pop();
 
            // Update sum of current level
            sum = sum + Value[temp];
 
            // Enqueue the children of
            // dequeued node
            for (int i = 0;
                 i < adj[temp].size(); i++) {
                q.push(adj[temp][i]);
            }
        }
 
        // Update maximum level sum
        result = max(sum, result);
    }
 
    // Return the result
    return result;
}
 
// Driver Code
int main()
{
    // Number of nodes
    int N = 10;
 
    // Edges of the N-ary tree
    int Edges[][2] = { { 0, 1 }, { 0, 2 },
                       { 0, 3 }, { 1, 4 },
                       { 1, 5 }, { 3, 6 },
                       { 6, 7 }, { 6, 8 },
                       { 6, 9 } };
    // Given cost
    vector Value = { 1, 2, -1, 3, 4,
                          5, 8, 6, 12, 7 };
 
    // Function call
    cout << maxLevelSum(N, N - 1,
                        Value, Edges);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
 
class GFG{
 
// Function to find the maximum sum
// a level in N-ary treeusing BFS
@SuppressWarnings("unchecked")
static int maxLevelSum(int N, int M, int[] Value,
                                     int Edges[][])
{
     
    // Stores the edges of the graph
    ArrayList[] adj = new ArrayList[N];
 
    for(int i = 0; i < N; i++)
    {
        adj[i] = new ArrayList<>();
    }
 
    // Create Adjacency list
    for(int i = 0; i < M; i++)
    {
        adj[Edges[i][0]].add(Edges[i][1]);
    }
 
    // Initialize result
    int result = Value[0];
 
    // Stores the nodes of each level
    Queue q = new LinkedList<>();
 
    // Insert root
    q.add(0);
 
    // Perform level order traversal
    while (!q.isEmpty())
    {
         
        // Count of nodes of the
        // current level
        int count = q.size();
 
        int sum = 0;
 
        // Traverse the current level
        while (count-- > 0)
        {
             
            // Dequeue a node from queue
            int temp = q.poll();
 
            // Update sum of current level
            sum = sum + Value[temp];
 
            // Enqueue the children of
            // dequeued node
            for(int i = 0; i < adj[temp].size(); i++)
            {
                q.add(adj[temp].get(i));
            }
        }
 
        // Update maximum level sum
        result = Math.max(sum, result);
    }
 
    // Return the result
    return result;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Number of nodes
    int N = 10;
 
    // Edges of the N-ary tree
    int[][] Edges = { { 0, 1 }, { 0, 2 },
                      { 0, 3 }, { 1, 4 },
                      { 1, 5 }, { 3, 6 },
                      { 6, 7 }, { 6, 8 },
                      { 6, 9 } };
    // Given cost
    int[] Value = { 1, 2, -1, 3, 4,
                    5, 8, 6, 12, 7 };
 
    // Function call
    System.out.println(maxLevelSum(N, N - 1,
                                   Value, Edges));
}
}
 
// This code is contributed by sanjeev2552


Python3
# Python3 program for the above approach
from collections import deque
 
# Function to find the maximum sum
# a level in N-ary treeusing BFS
def maxLevelSum(N, M, Value, Edges):
     
    # Stores the edges of the graph
    adj = [[] for i in range(N)]
 
    # Create Adjacency list
    for i in range(M):
        adj[Edges[i][0]].append(Edges[i][1])
 
    # Initialize result
    result = Value[0]
 
    # Stores the nodes of each level
    q = deque()
 
    # Insert root
    q.append(0)
 
    # Perform level order traversal
    while (len(q) > 0):
 
        # Count of nodes of the
        # current level
        count = len(q)
 
        sum = 0
 
        # Traverse the current level
        while (count):
 
            # Dequeue a node from queue
            temp = q.popleft()
 
            # Update sum of current level
            sum = sum + Value[temp]
 
            # Enqueue the children of
            # dequeued node
            for i in range(len(adj[temp])):
                q.append(adj[temp][i])
                 
            count -= 1
 
        # Update maximum level sum
        result = max(sum, result)
 
    # Return the result
    return result
 
# Driver Code
if __name__ == '__main__':
     
    # Number of nodes
    N = 10
 
    # Edges of the N-ary tree
    Edges = [ [ 0, 1 ], [ 0, 2 ],
              [ 0, 3 ], [ 1, 4 ],
              [ 1, 5 ], [ 3, 6 ],
              [ 6, 7 ], [ 6, 8 ],
              [ 6, 9 ] ]
               
    # Given cost
    Value = [ 1, 2, -1, 3, 4,
              5, 8, 6, 12, 7 ]
 
    # Function call
    print(maxLevelSum(N, N - 1,
                      Value, Edges))
 
# This code is contributed by mohit kumar 29


C#
// C# program for the
// above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to find the maximum sum
// a level in N-ary treeusing BFS
 
static int maxLevelSum(int N, int M,
                       int[] Value,
                       int [,]Edges)
{
  // Stores the edges of the graph
  List[] adj = new List[N];
 
  for(int i = 0; i < N; i++)
  {
    adj[i] = new List();
  }
 
  // Create Adjacency list
  for(int i = 0; i < M; i++)
  {
    adj[Edges[i, 0]].Add(Edges[i, 1]);
  }
 
  // Initialize result
  int result = Value[0];
 
  // Stores the nodes of each level
  Queue q = new Queue();
 
  // Insert root
  q.Enqueue(0);
 
  // Perform level order
  // traversal
  while (q.Count != 0)
  {
    // Count of nodes of the
    // current level
    int count = q.Count;
 
    int sum = 0;
 
    // Traverse the current
    // level
    while (count-- > 0)
    {
      // Dequeue a node from
      // queue
      int temp = q.Peek();
      q.Dequeue();
 
      // Update sum of current
      // level
      sum = sum + Value[temp];
 
      // Enqueue the children of
      // dequeued node
      for(int i = 0;
              i < adj[temp].Count; i++)
      {
        q.Enqueue(adj[temp][i]);
      }
    }
 
    // Update maximum level sum
    result = Math.Max(sum, result);
  }
 
  // Return the result
  return result;
}
 
// Driver Code
public static void Main(String[] args)
{   
  // Number of nodes
  int N = 10;
 
  // Edges of the N-ary tree
  int[,] Edges = {{0, 1}, {0, 2},
                  {0, 3}, {1, 4},
                  {1, 5}, {3, 6},
                  {6, 7}, {6, 8},
                  {6, 9}};
  // Given cost
  int[] Value = {1, 2, -1, 3, 4,
                 5, 8, 6, 12, 7};
 
  // Function call
  Console.WriteLine(maxLevelSum(N, N - 1,
                                Value, Edges));
}
}
 
// This code is contributed by Princi Singh


输出
25

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live