📌  相关文章
📜  N元树中每个级别的最大值

📅  最后修改于: 2021-04-21 21:28:15             🧑  作者: Mango

给定一个由值范围为[0,N – 1]的节点和数组arr []组成的N元树其中每个节点i与值arr [i]相关联,任务是打印与任何一个相关联的最大值给定N元树的每个级别上的节点。

例子:

方法:可通过执行给定树的级别顺序遍历来解决此问题。在遍历树时,分别处理每个级别的节点。对于正在处理的每个级别,请计算该级别中所有节点的最大值。请按照以下步骤操作:

  1. 将当前级别的所有子节点存储在一个队列中,并逐一弹出当前级别的节点。
  2. 查找当前级别的所有弹出节点的最大值。
  3. 打印在上述步骤中获得的最大值。
  4. 对给定树的每个级别执行上述步骤,并分别打印每个级别的最大值。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the maximum value
// at each level of N-ary tree
int maxAtLevel(int N, int M,
               vector Value,
               int Edges[][2])
{
    // Stores the adjacency list
    vector adj[N];
 
    // Create the adjacency list
    for (int i = 0; i < M; i++) {
        int u = Edges[i][0];
        int v = Edges[i][1];
        adj[u].push_back(v);
    }
 
    // Perform level order traversal
    // of nodes at each level
    queue q;
 
    // Push the root node
    q.push(0);
 
    // Iterate until queue is empty
    while (!q.empty()) {
 
        // Get the size of queue
        int count = q.size();
 
        int maxVal = 0;
 
        // Iterate for all the nodes
        // in the queue currently
        while (count--) {
 
            // Dequeue an node from queue
            int temp = q.front();
            q.pop();
 
            maxVal = max(maxVal,
                         Value[temp]);
 
            // Enqueue the children of
            // dequeued node
            for (int i = 0;
                 i < adj[temp].size();
                 i++) {
                q.push(adj[temp][i]);
            }
        }
 
        // Print the result
        cout << maxVal << " ";
    }
}
 
// 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
    maxAtLevel(N, N - 1, Value, Edges);
 
    return 0;
}


Java
// Java program for
// the above approach
import java.util.*;
class GFG{
 
// Function to find the maximum value
// at each level of N-ary tree
static void maxAtLevel(int N, int M,
                       int []Value,
                       int Edges[][])
{
  // Stores the adjacency list
  Vector []adj = new Vector[N];
   
  for (int i = 0; i < adj.length; i++)
    adj[i] = new Vector();
 
  // Create the adjacency list
  for (int i = 0; i < M; i++)
  {
    int u = Edges[i][0];
    int v = Edges[i][1];
    adj[u].add(v);
  }
 
  // Perform level order traversal
  // of nodes at each level
  Queue q = new LinkedList<>();
 
  // Push the root node
  q.add(0);
 
  // Iterate until queue is empty
  while (!q.isEmpty())
  {
    // Get the size of queue
    int count = q.size();
 
    int maxVal = 0;
 
    // Iterate for all the nodes
    // in the queue currently
    while (count-- > 0)
    {
      // Dequeue an node from queue
      int temp = q.peek();
      q.remove();
 
      maxVal = Math.max(maxVal, Value[temp]);
 
      // Enqueue the children of
      // dequeued node
      for (int i = 0;
               i < adj[temp].size(); i++)
      {
        q.add(adj[temp].get(i));
      }
    }
 
    // Print the result
    System.out.print(maxVal + " ");
  }
}
 
// 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
  maxAtLevel(N, N - 1, Value, Edges);
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program for the above approach
 
# Function to find the maximum value
# at each level of N-ary tree
def maxAtLevel(N, M, Value, Edges):
     
    # Stores the adjacency list
    adj = [[] for i in range(N)]
 
    # Create the adjacency list
    for i in range(M):
        u = Edges[i][0]
        v = Edges[i][1]
        adj[u].append(v)
 
    # Perform level order traversal
    # of nodes at each level
    q = []
 
    # Push the root node
    q.append(0)
 
    # Iterate until queue is empty
    while (len(q)):
         
        # Get the size of queue
        count = len(q)
 
        maxVal = 0
 
        # Iterate for: all the nodes
        # in the queue currently
        while (count):
             
            # Dequeue an node from queue
            temp = q[0]
            q.remove(q[0])
 
            maxVal = max(maxVal, Value[temp])
 
            # Enqueue the children of
            # dequeued node
            for i in range(len(adj[temp])):
                q.append(adj[temp][i])
                 
            count -= 1
 
        # Print the result
        print(maxVal, end = " ")
 
# 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
    maxAtLevel(N, N - 1, Value, Edges)
 
# This code is contributed by ipg2016107


C#
// C# program for
// the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to find the
// maximum value at each
// level of N-ary tree
static void maxAtLevel(int N, int M,
                       int []Value,
                       int [,]Edges)
{
  // Stores the adjacency list
  List []adj = new List[N];
 
  for (int i = 0; i < adj.Length; i++)
    adj[i] = new List();
 
  // Create the adjacency list
  for (int i = 0; i < M; i++)
  {
    int u = Edges[i, 0];
    int v = Edges[i, 1];
    adj[u].Add(v);
  }
 
  // Perform level order traversal
  // of nodes at each level
  Queue q = new Queue();
 
  // Push the root node
  q.Enqueue(0);
 
  // Iterate until queue is empty
  while (q.Count != 0)
  {
    // Get the size of queue
    int count = q.Count;
 
    int maxVal = 0;
 
    // Iterate for all the nodes
    // in the queue currently
    while (count-- > 0)
    {
      // Dequeue an node from queue
      int temp = q.Peek();
      q.Dequeue();
 
      maxVal = Math.Max(maxVal,
                        Value[temp]);
 
      // Enqueue the children of
      // dequeued node
      for (int i = 0;
               i < adj[temp].Count; i++)
      {
        q.Enqueue(adj[temp][i]);
      }
    }
 
    // Print the result
    Console.Write(maxVal + " ");
  }
}
 
// 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
  maxAtLevel(N, N - 1, Value, Edges);
}
}
 
// This code is contributed by 29AjayKumar


输出:
1 3 8 12









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