📜  空值二叉树的最大宽度

📅  最后修改于: 2021-10-27 09:01:11             🧑  作者: Mango

给定一个由N 个节点组成的二叉树,任务是找到给定树的最大宽度,其中最大宽度定义为给定树的每一级所有宽度的最大值。

例子:

方法:给定的问题可以通过将二叉树表示为堆的数组表示来解决。假设一个节点的索引是i那么他们的孩子的索引是(2*i + 1)(2*i + 2) 。现在,对于每个级别,找到每个级别中最左侧节点和最右侧节点的位置,然后它们之间的差异将给出该级别的宽度。请按照以下步骤解决此问题:

  • 初始化两个HashMap,比如HMMaxHMMin ,分别存储了每一层最左边节点和最右边节点的位置
  • 创建一个递归函数getMaxWidthHelper(root, lvl, i) ,它取树的根,树的起始层初始为0 ,树的根节点的位置初始为0并执行以下步骤:
    • 如果树的根为NULL ,则返回。
    • 将最左边的节点索引存储在HMMin中的级别lvl
    • 将最右边的节点索引存储在HMMax中的级别lvl中。
    • 通过将lvl的值更新为lvl + 1并将i的值更新为(2*i + 1) ,递归地调用左子树。
    • 通过将lvl的值更新为lvl + 1并将i的值更新为(2*i + 2) ,递归地调用右子树。
  • 调用函数getMaxWidthHelper(root, 0, 0)来填充 HashMap。
  • 完成上述步骤后,打印(HMMax(L) – HMMin(L)+ 1)的最大值电平L的所有可能的值之一。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Tree Node structure
struct Node
{
    int data;
    Node *left, *right;
     
    // Constructor
    Node(int item)
    {
        data = item;
        left = right = NULL;
    }
};
 
Node *root;
int maxx = 0;
 
// Stores the position of leftmost
// and rightmost node in each level
map hm_min;
map hm_max;
 
// Function to store the min and the
// max index of each nodes in hashmaps
void getMaxWidthHelper(Node *node,
                       int lvl, int i)
{
     
    // Base Case
    if (node == NULL)
    {
        return;
    }
 
    // Stores rightmost node index
    // in the hm_max
    if (hm_max[lvl])
    {
        hm_max[lvl] = max(i, hm_max[lvl]);
    }
    else
    {
        hm_max[lvl] = i;
    }
 
    // Stores leftmost node index
    // in the hm_min
    if (hm_min[lvl])
    {
        hm_min[lvl] = min(i, hm_min[lvl]);
    }
 
    // Otherwise
    else
    {
        hm_min[lvl] = i;
    }
 
    // If the left child of the node
    // is not empty, traverse next
    // level with index = 2*i + 1
    getMaxWidthHelper(node->left, lvl + 1,
                                2 * i + 1);
 
    // If the right child of the node
    // is not empty, traverse next
    // level with index = 2*i + 2
    getMaxWidthHelper(node->right, lvl + 1,
                                 2 * i + 2);
}
 
// Function to find the maximum
// width of the tree
int getMaxWidth(Node *root)
{
     
    // Helper function to fill
    // the hashmaps
    getMaxWidthHelper(root, 0, 0);
 
    // Traverse to each level and
    // find the maximum width
    for(auto lvl : hm_max)
    {
        maxx = max(maxx, hm_max[lvl.second] -
                         hm_min[lvl.second] + 1);
    }
 
    // Return the result
    return maxx;
}
 
// Driver Code
int main()
{
     
    /*
    Constructed binary tree is:
          1
        /  \
       2    3
     /  \    \
    4   5     8
             /  \
            6   7
     */
    root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    root->right->right = new Node(8);
    root->right->right->left = new Node(6);
    root->right->right->right = new Node(7);
 
    // Function Call
    cout << (getMaxWidth(root));
}
 
// This code is contributed by mohit kumar 29


Java
// Java program for the above approach
 
import java.util.*;
 
// Tree Node structure
class Node {
    int data;
    Node left, right;
 
    // Constructor
    Node(int item)
    {
        data = item;
        left = right = null;
    }
}
 
// Driver Code
public class Main {
 
    Node root;
    int maxx = 0;
 
    // Stores the position of leftmost
    // and rightmost node in each level
    HashMap hm_min
        = new HashMap<>();
    HashMap hm_max
        = new HashMap<>();
 
    // Function to store the min and the
    // max index of each nodes in hashmaps
    void getMaxWidthHelper(Node node,
                           int lvl, int i)
    {
        // Base Case
        if (node == null) {
            return;
        }
 
        // Stores rightmost node index
        // in the hm_max
        if (hm_max.containsKey(lvl)) {
            hm_max.put(lvl,
                       Math.max(
                           i, hm_max.get(lvl)));
        }
        else {
            hm_max.put(lvl, i);
        }
 
        // Stores leftmost node index
        // in the hm_min
        if (hm_min.containsKey(lvl)) {
            hm_min.put(lvl,
                       Math.min(
                           i, hm_min.get(lvl)));
        }
 
        // Otherwise
        else {
            hm_min.put(lvl, i);
        }
 
        // If the left child of the node
        // is not empty, traverse next
        // level with index = 2*i + 1
        getMaxWidthHelper(node.left, lvl + 1,
                          2 * i + 1);
 
        // If the right child of the node
        // is not empty, traverse next
        // level with index = 2*i + 2
        getMaxWidthHelper(node.right, lvl + 1,
                          2 * i + 2);
    }
 
    // Function to find the maximum
    // width of the tree
    int getMaxWidth(Node root)
    {
        // Helper function to fill
        // the hashmaps
        getMaxWidthHelper(root, 0, 0);
 
        // Traverse to each level and
        // find the maximum width
        for (Integer lvl : hm_max.keySet()) {
            maxx
                = Math.max(
                    maxx,
                    hm_max.get(lvl)
                        - hm_min.get(lvl) + 1);
        }
 
        // Return the result
        return maxx;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        Main tree = new Main();
 
        /*
        Constructed binary tree is:
              1
            /  \
           2    3
         /  \    \
        4   5     8
                 /  \
                6   7
         */
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(4);
        tree.root.left.right = new Node(5);
        tree.root.right.right = new Node(8);
        tree.root.right.right.left = new Node(6);
        tree.root.right.right.right = new Node(7);
 
        // Function Call
        System.out.println(
            tree.getMaxWidth(
                tree.root));
    }
}


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG {
     
    // A Binary Tree Node
    class Node
    {
        public int data;
        public Node left;
        public Node right;
      
        public Node(int item)
        {
            data = item;
            left = right = null;
        }
    };
     
    static int maxx = 0;
  
    // Stores the position of leftmost
    // and rightmost node in each level
    static Dictionary hm_min = new Dictionary();
    static Dictionary hm_max = new Dictionary();
  
    // Function to store the min and the
    // max index of each nodes in hashmaps
    static void getMaxWidthHelper(Node node,
                           int lvl, int i)
    {
        // Base Case
        if (node == null) {
            return;
        }
  
        // Stores rightmost node index
        // in the hm_max
        if (hm_max.ContainsKey(lvl)) {
            hm_max[lvl] = Math.Max(i, hm_max[lvl]);
        }
        else {
            hm_max[lvl] = i;
        }
  
        // Stores leftmost node index
        // in the hm_min
        if (hm_min.ContainsKey(lvl)) {
            hm_min[lvl] = Math.Min(i, hm_min[lvl]);
        }
  
        // Otherwise
        else {
            hm_min[lvl] = i;
        }
  
        // If the left child of the node
        // is not empty, traverse next
        // level with index = 2*i + 1
        getMaxWidthHelper(node.left, lvl + 1,
                          2 * i + 1);
  
        // If the right child of the node
        // is not empty, traverse next
        // level with index = 2*i + 2
        getMaxWidthHelper(node.right, lvl + 1,
                          2 * i + 2);
    }
  
    // Function to find the maximum
    // width of the tree
    static int getMaxWidth(Node root)
    {
        // Helper function to fill
        // the hashmaps
        getMaxWidthHelper(root, 0, 0);
  
        // Traverse to each level and
        // find the maximum width
        foreach (KeyValuePair lvl in hm_max) {
            maxx = Math.Max(maxx, hm_max[lvl.Key] - hm_min[lvl.Key] + 1);
        }
  
        // Return the result
        return maxx;
    }
   
  // Driver code
  static void Main()
  {
  
    /*
    Constructed binary tree is:
          1
        /  \
       2    3
     /  \    \
    4   5     8
             /  \
            6   7
     */
    Node root = new Node(1);
    root.left = new Node(2);
    root.right = new Node(3);
    root.left.left = new Node(4);
    root.left.right = new Node(5);
    root.right.right = new Node(8);
    root.right.right.left = new Node(6);
    root.right.right.right = new Node(7);
 
    // Function Call
    Console.Write(getMaxWidth(root));
  }
}
 
// This code is contributed by divyeshrabadiya07.


Javascript


输出:
4

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程