ProDeveloperTutorial.com

教程和编程解决方案
菜单
  • Shell脚本
  • 系统设计
  • Linux系统编程
  • 4g LTE
  • 编码问题
  • C
  • C ++
  • DSA
  • GIT

获取二叉树的最大宽度

前开发者教程 2020年10月8日

题:

给定二叉树的根节点,获取该树的最大宽度

例:

考虑下图

二元树

级别1的宽度为1。因为它只有1个节点。
级别2的宽度为2。因为它只有2个节点。
级别3的宽度为4。因为它只有4个节点。

解:

在进行级别顺序遍历时,计算每个级别上的节点数。

然后获取每个级别的最大节点数并显示结果。

解

#include <iostream>
#include <queue>
#include <stack>
using namespace std;

// structure to hold binary tree node
struct Node
{
    int data;
    Node *left, *right;

    Node(int data)
    {
        this->data = data;
        this->left = this->right = nullptr;
    }
};

int get_max_width(Node *root) 
{ 
    if (root == NULL) 
        return 0; 
  
    int result = 0; 
  
    queue<Node*> q; 
    q.push(root); 
    while (!q.empty()) 
    { 
        //get the size of the queue
        int count = q.size() ; 

        result = max(count, result); 
  
        //this loop will get all the nodes at a particular level
        while (count > 0) 
        { 
            Node *temp = q.front(); 
            q.pop(); 
  
            if (temp->left != NULL) 
                q.push(temp->left); 
            if (temp->right != NULL) 
                q.push(temp->right); 

            count --;
        } 
    } 
  
    return result; 
} 

int main()  
{  
    Node* root = nullptr;
    /* Binary tree:
              16
            /   \
           /     \
          10      25
         /  \    /  \
        /    \  /    \
       7    15 18     30

    */

    root = new Node(16);
    root->left = new Node(10);
    root->right = new Node(25);
    root->left->left = new Node(7);
    root->left->right = new Node(15);
    root->right->left = new Node(18);
    root->right->right = new Node(30);

    cout<<"The max width of the binary tree is = "<< get_max_width(root)<<endl;

    return 0;  
}  

输出:

The max width of the binary tree is = 4
分享
电子邮件
鸣叫
领英
Reddit
绊倒
Pinterest的
上一篇文章
下一篇

关于作者

前开发者教程

每天我们都会讨论竞争性编程问题,请加入我们的网站:   电报频道

ProDeveloperTutorial.com

教程和编程解决方案
版权© 2020 ProDeveloperTutorial.com
从以下课程获得热门课程: 教育性的



  • <dir id="w9D5URv"></dir>




  • <q id="owK9RH4"><caption id="MNYGWqr" class="M5NmxFH"><s class="BHg9e0w"></s></caption></q>

    <address id="vTbsqFo" class="vPAgVFP"></address>

    <samp id="fnxwHU3" class="fjPSPxE"></samp>