求解一个二叉树的最大宽度(层次遍历)

定义一个二叉树

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

class Node{
public:
    int value;
    Node* left;
    Node* right;
    Node(int value):value(value){
        left = nullptr;
        right = nullptr;
    }
};
//求解二叉树的最大宽度(层次遍历)
int maxBoard(Node *head){
    if(head==nullptr){
        return 0;
    }
    queue<Node *>q; //init a queue
    unordered_map<Node*, int> hashMap;
    //Node是在第几层
    hashMap.insert(pair<Node*,int>(head,1));
    q.push(head);
    int curLayer = 1;
    int curNodes = 0;
    int maxNodes = INT_MIN;
    while(!q.empty()){
        head = q.front();
        int currentLayer = hashMap[head];
        if(currentLayer == curLayer){
            curNodes+=1;
        } else{
            maxNodes = max(maxNodes, curNodes);
            curLayer ++;
            curNodes = 1;
        }
        q.pop();
        if(head->left!=nullptr){
            q.push(head->left);
            hashMap.insert(
                    pair<Node*,int>(head->left,curLayer+1));
        }
        if(head->right!=nullptr){
            q.push(head->right);
            hashMap.insert(
                    pair<Node*,int>(head->right,curLayer+1));
        }
    }
    return max(maxNodes,curNodes);
}
posted @ 2021-08-03 18:05  蘑菇王国大聪明  阅读(221)  评论(0编辑  收藏  举报