📜  一元树的最大宽度

📅  最后修改于: 2021-04-26 18:50:38             🧑  作者: Mango

给定一棵N元树,任务是找到给定树的最大宽度。树的最大宽度是所有级别之间的最大宽度。

例子:

方法:可以使用BFS解决此问题。这个想法是执行树的级别顺序遍历。遍历时,请分别处理不同级别的节点。对于正在处理的每个级别,计算每个级别上存在的节点数,并跟踪最大数量。请按照以下步骤解决问题:

  1. 初始化一个变量,例如maxWidth,以存储所需的树的最大宽度。
  2. 初始化队列以执行给定树的级别顺序遍历。
  3. 将根节点推入队列。
  4. 如果队列的大小超过maxWidth任何级别,然后更新maxWidth 队列的大小。
  5. 遍历队列并将下一级别的所有节点推入队列,然后弹出当前级别的所有节点。
  6. 重复上述步骤,直到遍历树的所有级别。
  7. 最后,返回maxWidth的最终值。

下面是上述方法的实现:

C++
4
                 / | \
                2  3 -5
               / \    /\
             -1   3 -2  6


Java
1
            / | \
           2  -1  3
         /  \      \
        4    5      8
      /           / | \
     2           6  12  7  


Python3
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to find the maximum width of
// the tree using level order traversal
int maxWidth(int N, int M,
             vector cost,
             vector > s)
{
    // Store the edges of the tree
    vector adj[N];
    for (int i = 0; i < M; i++) {
        adj[s[i][0]].push_back(
            s[i][1]);
    }
 
    // Stores maximum width
    // of the tree
    int result = 0;
 
    // Stores the nodes
    // of each level
    queue q;
 
    // Insert root node
    q.push(0);
 
    // Perform level order
    // traversal on the tree
    while (!q.empty()) {
 
        // Stores the size of
        // the queue
        int count = q.size();
 
        // Update maximum width
        result = max(count, result);
 
        // Push the nodes of the next
        // level and pop the elements
        // of the current level
        while (count--) {
 
            // Get element from the
            // front the Queue
            int temp = q.front();
            q.pop();
 
            // Push all nodes of the next level.
            for (int i = 0; i < adj[temp].size();
                 i++) {
                q.push(adj[temp][i]);
            }
        }
    }
 
    // Return the result.
    return result;
}
 
// Driver Code
int main()
{
    int N = 11, M = 10;
 
    vector > edges;
    edges.push_back({ 0, 1 });
    edges.push_back({ 0, 2 });
    edges.push_back({ 0, 3 });
    edges.push_back({ 1, 4 });
    edges.push_back({ 1, 5 });
    edges.push_back({ 3, 6 });
    edges.push_back({ 4, 7 });
    edges.push_back({ 6, 10 });
    edges.push_back({ 6, 8 });
    edges.push_back({ 6, 9 });
 
    vector cost
        = { 1, 2, -1, 3, 4, 5,
            8, 2, 6, 12, 7 };
 
    /* Constructed tree is:
                1
              / | \
            2  -1  3
          /  \      \
         4    5      8
        /          / | \
       2          6  12  7
    */
 
    cout << maxWidth(N, M, cost, edges);
 
    return 0;
}


C#
// Java program to implement
// the above approach
import java.io.*;
import java.util.*;
class GFG
{
   
    // Function to find the maximum width of
    // the tree using level order traversal
    static int maxWidth(int N, int M,ArrayList cost,
                        ArrayList > s)
    {
       
        // Store the edges of the tree
        ArrayList > adj =
          new ArrayList >();
        for(int i = 0; i < N; i++)
        {
            adj.add(new ArrayList());
        }
        for(int i = 0; i < M; i++)
        {
            adj.get(s.get(i).get(0)).add(s.get(i).get(1));
        }
       
        // Stores maximum width
        // of the tree
        int result = 0;
       
        // Stores the nodes
        // of each level
        Queue q = new LinkedList<>();
       
        // Insert root node
        q.add(0);
       
        // Perform level order
        // traversal on the tree
        while(q.size() != 0)
        {
           
            // Stores the size of
            // the queue
            int count = q.size();
           
            // Update maximum width
            result = Math.max(count, result);
           
            // Push the nodes of the next
            // level and pop the elements
            // of the current level
            while(count-->0)
            {
               
                // Get element from the
                // front the Queue
                 int temp = q.remove();
               
                // Push all nodes of the next level.
                 for(int i = 0; i < adj.get(temp).size(); i++)
                 {
                     q.add(adj.get(temp).get(i));
                 }
            }
        }
       
        // Return the result.
        return result;
    }
   
    // Driver Code
    public static void main (String[] args)
    {
        int N = 11, M = 10;
        ArrayList > edges = new ArrayList >();
        edges.add(new ArrayList(Arrays.asList( 0, 1)));
        edges.add(new ArrayList(Arrays.asList( 0, 2)));
        edges.add(new ArrayList(Arrays.asList( 0, 3)));
        edges.add(new ArrayList(Arrays.asList(1,4)));
        edges.add(new ArrayList(Arrays.asList(1,5)));
        edges.add(new ArrayList(Arrays.asList(3,6)));
        edges.add(new ArrayList(Arrays.asList(4,7)));
        edges.add(new ArrayList(Arrays.asList(6,10)));
        edges.add(new ArrayList(Arrays.asList(6,8)));
        edges.add(new ArrayList(Arrays.asList(6,9)));
 
        ArrayList cost = new ArrayList(Arrays.asList(1, 2, -1, 3, 4, 5,8, 2, 6, 12, 7 ));       
        /* Constructed tree is:
                1
              / | \
            2  -1  3
          /  \      \
         4    5      8
        /          / | \
       2          6  12  7
    */
        System.out.println(maxWidth(N, M, cost, edges));
    }
}
 
// This code is contributed by avanitrachhadiya2155


输出:
# Python3 program to implement
# the above approach
from collections import deque
 
# Function to find the maximum width of
#. he tree using level order traversal
def maxWidth(N, M, cost, s):
     
    # Store the edges of the tree
    adj = [[] for i in range(N)]
    for i in range(M):
        adj[s[i][0]].append(s[i][1])
 
    # Stores maximum width
    # of the tree
    result = 0
 
    # Stores the nodes
    # of each level
    q = deque()
 
    # Insert root node
    q.append(0)
 
    # Perform level order
    # traversal on the tree
    while (len(q) > 0):
 
        # Stores the size of
        # the queue
        count = len(q)
 
        # Update maximum width
        result = max(count, result)
 
        # Push the nodes of the next
        # level and pop the elements
        # of the current level
        while (count > 0):
 
            # Get element from the
            # front the Queue
            temp = q.popleft()
 
            # Push all nodes of the next level.
            for i in adj[temp]:
                q.append(i)
                 
            count -= 1
 
    # Return the result.
    return result
 
# Driver Code
if __name__ == '__main__':
     
    N = 11
    M = 10
 
    edges = []
    edges.append([0, 1])
    edges.append([0, 2])
    edges.append([0, 3])
    edges.append([1, 4])
    edges.append([1, 5])
    edges.append([3, 6])
    edges.append([4, 7])
    edges.append([6, 1])
    edges.append([6, 8])
    edges.append([6, 9])
 
    cost = [ 1, 2, -1, 3, 4, 5,
             8, 2, 6, 12, 7]
     
    # Constructed tree is:
    #           1
    #         / | \
    #        2 -1  3
    #       / \       \
    #      4   5        8
    #     /          / | \
    #  2         6  12  7
    print(maxWidth(N, M, cost, edges))
 
# This code is contributed by mohit kumar 29

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