求解一个二叉树的最大宽度(层次遍历)
定义一个二叉树
#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);
}
主要是给自己看的,所以肯定会出现很多错误哈哈哈哈哈